Keith Beard
Keith Beard

Reputation: 1611

Recursive function examples in VB.Net

I have seen other posts, but they are mostly in C#. For someone looking to learn recursion, seeing real world working examples in VB.Net could prove helpful. It's an added difficulty to try to decipher and convert C# if someone is just getting their feet wet programming in VB.Net. I did find this post which I understand now, but if there had been a post of VB.Net examples, I may have been able to pick it up faster.This is in part why I am asking this question:

Can anyone could show some simple examples of recursion functions in VB.Net?

Upvotes: 4

Views: 26627

Answers (4)

mchar
mchar

Reputation: 158

This is a recursion example direct from msdn for VB.NET 2012:

Function factorial(ByVal n As Integer) As Integer
    If n <= 1 Then 
        Return 1
    Else 
        Return factorial(n - 1) * n
    End If 
End Function

Reference

Upvotes: 0

dbasnett
dbasnett

Reputation: 11773

One of the classics

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Try
        Label1.Text = Factorial(20).ToString("n0")
    Catch ex As Exception
        Debug.WriteLine("error")
    End Try
End Sub

Function Factorial(ByVal number As Long) As Long
    If number <= 1 Then
        Return (1)
    Else
        Return number * Factorial(number - 1)
    End If
End Function 'Factorial

In .Net 4.0 you could use BigInteger instead of Long...

Upvotes: 1

CodingBarfield
CodingBarfield

Reputation: 3398

This one from the wiki article is great

Sub walkTree(ByVal directory As IO.DirectoryInfo, ByVal pattern As String)
 For Each file In directory.GetFiles(pattern)
    Console.WriteLine(file.FullName)
 Next
 For Each subDir In directory.GetDirectories
    walkTree(subDir, pattern)
 Next
End Sub

Upvotes: 3

KV Prajapati
KV Prajapati

Reputation: 94625

Take a look at MSDN article - Recursive Procedures (Visual Basic). This article will help you to understand the basics of recursion.

Please refer the following links:

  1. Recursive function to read a directory structure
  2. Recursion, why it's cool.

Upvotes: 3

Related Questions