ARTICLE

Use of Recursion in VB.NET

Posted by Sapna Articles | Visual Basic Language June 17, 2011
Recursion is the process where a method can call itself.
Download Files:
 
Reader Level:

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

Figure 1

Login to add your contents and source code to this article
share this article :
post comment
 
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
Become a Sponsor