HomeSearch

VB.NET Recursion Example

Develop and call recursive Functions. Learn how to use ByRef arguments in recursion.

Recursion occurs when a method calls itself. Recursive functions need special stop conditions. Otherwise they will infinitely continue calling themselves. With the ByRef keyword, we provide a way to stop a recursive function.ByVal, ByRef

Example. The Recursive() Function receives two arguments. The first argument is a value that is doubled on each call. The second argument is received ByRef—it exists in one memory place and it is incremented on every function invocation.

Count: The count represents the total number of times the Function has been called, no matter the calling pattern.

Output: Let's examine the output of the program. We see that the Recursive function is called six times.

And: After 5 is multiplied by 2 five times, we have the result 160. On the sixth function call, the multiplication does not occur.

VB.NET program that uses recursive method Module Module1 Function Recursive(ByVal value As Integer, ByRef count As Integer) As Integer Console.WriteLine("Recursive({0}, {1})", value, count) count = count + 1 If value >= 100 Then Return value End If Return Recursive(value * 2, count) End Function Sub Main() Dim count As Integer = 0 Dim total As Integer = Recursive(5, count) Console.WriteLine("Total = {0}", total) Console.WriteLine("Count = {0}", count) End Sub End Module Output Recursive(5, 0) Recursive(10, 1) Recursive(20, 2) Recursive(40, 3) Recursive(80, 4) Recursive(160, 5) Total = 160 Count = 6

ByRef. What is the importance of ByRef when making recursive method calls? Let's say you want to terminate an algorithm after 1000 method calls. If you use ByRef, this is possible no matter the calling order of the functions.

However, if you don't use ByRef, you cannot terminate the algorithm in this way. The arguments will be copied to further calls without being changed by previous calls from the same function.

Tip: You could always just use a shared variable. This can be harder to maintain, as it must be reset on the first call.

Summary. Recursion is a fascinating topic in computer science. This glimpse of recursion in VB.NET is not comprehensive, but the usage of ByRef in recursive algorithms is useful. Recursion can be always rewritten as iteration.

And: In critical programs, iteration is typically more reliable and easy to debug, and thus preferred.

Home
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.