How to Call a Subroutine From Within Itself in Visual Basic
- 1). Create a new Visual Basic function. For example:
Function gcd(ByVal x As Integer, ByVal y as Integer) As Integer
End Function
This function will compute the greatest common divisor of two numbers. - 2). Add a test between the Function and End Function lines to distinguish between the "base case" and the "recursive case." Base cases are very important in recursive functions--without one, your code will usually cause an infinite loop and likely crash your program. For example, the base case for the "gcd" function looks like this:
If y = 0 Then
' This will be the base case
Else
' This will be the recursive case
End If - 3). Add a base case. This is the value that your function returns when it encounters a problem so small that it can't break it down any further. For the "gcd" function, it looks like this:
Return x - 4). Add a recursive case. When your function recurs, it invokes itself with a simpler problem that will help it solve the bigger problem. In the case of the "gcd" function, the simpler problem is chosen so that its result is actually the result for the whole complex problem. It looks like this:
Return gcd(y, x Mod y) - 5). Test your function. It's always important to test recursive functions using the base case and some recursive cases as input. Try to think of tests that might be outside of the norm, such as negative numbers.
Source...