VB.NET Recursion

Recursion is the process where a method can call itself.
  • 7551
 

Recursion is the process where a method can call itself. I simple term, it is the process of calling a function from within the same function. Recursion seems like to call itself.

For Example, when you put two mirror parallel position on that time recursion happen because each mirror create  infinite form of its image.

imageofRecursion.gif

To show you how recursion method works. I have created factorial function because to get factorial of any integer factorial function must call itself. Factorial of 3 must be 6. See the below code.

Code

Module
Module1
    Sub Main()
         
Dim f As New Fact()
         
Console.WriteLine("Factorial of 3 is :" & f.factorial(3))
         
Console.WriteLine("Factorial of 4 is :" & f.factorial(4))
         
Console.WriteLine("Factorial of 5 is :" & f.factorial(5))
         
Console.WriteLine("Factorial of 6 is :" & f.factorial(6))
         
Console.WriteLine("Factorial of 7 is :" & f.factorial(7))
         
Console.WriteLine("Factorial of 8 is :" & f.factorial(8))
         
Console.WriteLine("Factorial of 9 is :" & f.factorial(9))
         
Console.WriteLine("Factorial of 10 is :" & f.factorial(10))
         
Console.WriteLine("Factorial of 11 is :" & f.factorial(11))
         
Console.WriteLine("Factorial of 12 is :" & f.factorial(12))
         
Console.WriteLine("Factorial of 13 is :" & f.factorial(13))
         
Console.ReadLine()
     
End Sub
 
    Class Fact
         Public Function factorial(n As Integer) As Long
             Dim result As Long
             If n = 1 Then
                 Return 1
             
Else
 
                result = factorial(n - 1) * n
                 
Return result
             
End If
 
        End Function
     End Class
End Module

Output

output.gif

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.