VB.Net/Language Basics/Function Recursive

Материал из VB Эксперт
Версия от 12:42, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Calculating factorials using recursion

Imports System
Public Class MainClass
    Shared Sub Main(ByVal args As String())
      Dim value As Integer = Convert.ToInt32(12)
      Dim i As Integer
      For i = 0 To value
         Console.WriteLine( i & "! = " & Factorial(i) & vbCrLf )
      Next
    End Sub
   " recursively generates factorial of number
   Shared Function Factorial(ByVal number As Long) As Long
      If number <= 1 Then " base case
         Return 1
      Else
         Return number * Factorial(number - 1)
      End If
   End Function " Factorial
End Class


Display directories on your drive recursively

Imports System
Imports System.IO

Public Class MainClass
   Shared Sub Main()
      Dim dirInfo As New DirectoryInfo("C:\")
      ListDirectories(dirInfo)
   End Sub 
  Shared Sub ListDirectories(ByVal theDirectory As DirectoryInfo)
    Dim tempDir As DirectoryInfo
    Console.WriteLine(theDirectory.FullName())
    For Each tempDir In theDirectory.GetDirectories()
      ListDirectories(tempDir)
    Next
  End Sub
End Class


Function Recursive

Imports System

Public Class MainClass
   Shared Sub Main()
    Console.WriteLine("The GCD of 36 and 99 is " & GCD(36, 99))
   End Sub 
  Shared Function GCD(ByVal p As Long, ByVal q As Long) As Long
    If Q Mod P = 0 Then
      Return P
    Else
      Return GCD(Q, P Mod Q)
    End If
  End Function
End Class


Recursive Function Demo

Imports System
Imports System.Diagnostics

Public Class MainClass
    Shared Sub Main()
        Dim N As Long = 10
        Dim result As Long = Fibo(N)
        Console.WriteLine(result)
    End Sub
    Private Shared Function Fibo(ByVal n As Long) As Long
        If n <= 2 Then Return n
        Return Fibo(n - 1) + Fibo(n - 2)
    End Function
End Class