Function Factorial Learn programming Visual Basic (VB.net)

Lesson:

Functions


Exercise:

Function Factorial


Objetive:

The factorial of a number is expressed as follows:

n! = n · (n-1) · (n-2) · (n-3) · ... · 3 · 2 · 1

For example,
6! = 6·5·4·3·2·1

Create a recursive function to calculate the factorial of the number specified as parameter:

Console.Write ( Factorial (6) );

would display 720


Code:

Imports System
Public Class Exercise114
    Public Shared Function Factorial(ByVal num As Integer) As Integer
        If num = 0 Then
            Return 1
        Else
            Return num * Factorial(num - 1)
        End If
    End Function

    Public Shared Sub Main()
        Console.WriteLine("Enter a number:")
        Dim number As Integer = Convert.ToInt32(Console.ReadLine())
        Console.WriteLine(Factorial(number))
        Console.WriteLine(Factorial(6))
    End Sub
End Class

Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.