Function recursive power Learn programming Visual Basic (VB.net)

Lesson:

Functions


Exercise:

Function recursive power


Objetive:

Create a function that calculates the result of raising an integer to another integer (eg 5 raised to 3 = 53 = 5 × 5 × 5 = 125). This function must be created recursively.

An example of use would be: Console.Write( Power(5,3) );


Code:

Imports System
Public Class exercise108
    Public Shared Sub Main()
        Dim number As Integer
        Dim exponent As Integer
        Console.Write("Base: ")
        number = Convert.ToInt32(Console.ReadLine())
        Console.Write("Exponent: ")
        exponent = Convert.ToInt32(Console.ReadLine())
        Console.WriteLine("{0}^{1}={0}", Power(number, exponent))
    End Sub

    Public Shared Function Power(ByVal number As Integer, ByVal exponent As Integer) As Integer
        If exponent = 0 Then
            Return 1
        Else
            Return number * Power(number, exponent - 1)
        End If
    End Function
End Class

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