CST2601 Visual Basic I
Notes on Function programming


Here is a short program.  The code is shown below.

I am demonstrating how to call a function called "FactReg" which computes a factorial in a straight forward method of using a loop.

The other function is called "FactRecur" which also computes a factorial.  However this function does it recursively.

Both functions yield identical results.


' Program calculates factorials non recursively and recursively.
Option Explicit ' General declaration

Private Sub cmdCalculateRegular_Click()
Dim x As Integer, n As Integer

Call lstValuesRegular.Clear ' Clear lstValues
n = txtInput.Text ' Get input

' Calculate a regular factorial function
For x = 0 To n
lstValuesRegular.AddItem Format$(x, "@@") & "! = " & _
FactReg((x)) ' Call-by-value
Next x

End Sub


Private Function FactReg(ByVal y As Double) As Double
Dim result As Double
Dim i As Integer

result = 1
For i = 1 To y
result = result * i
Next i
FactReg = result

End Function


Private Sub cmdCalculateRecursive_Click()
Dim x As Integer, n As Integer

Call lstValuesRecursive.Clear ' Clear lstValues
n = txtInput.Text ' Get input

' Calculate a recursive factorial function
For x = 0 To n
lstValuesRecursive.AddItem Format$(x, "@@") & "! = " & _
FactRecur((x)) ' Call-by-value
Next x

End Sub


Private Function FactRecur(ByVal y As Double) As Double

If y <= 1 Then
FactRecur = 1 ' Base case
Else
FactRecur = y * FactRecur(y - 1) ' Recursive step
End If

End Function