Exercise
Function Recursive Power
Objective
Write a C# 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) );
Write Your C# Exercise
C# Exercise Example
// Importing the System namespace to access basic system functions
using System;
class Program
{
// Recursive function to calculate the power of a number raised to another number
public static int Power(int baseNumber, int exponent)
{
// Base case: If the exponent is 0, return 1 (any number raised to the power of 0 is 1)
if (exponent == 0)
{
return 1;
}
// Recursive case: Multiply the base number by the result of calling Power with the exponent - 1
return baseNumber * Power(baseNumber, exponent - 1);
}
// Main method where the Power function is called
public static void Main()
{
// Declare two integers: base and exponent
int baseNumber = 5;
int exponent = 3;
// Call the recursive Power function and print the result
Console.WriteLine("The result of {0} raised to the power of {1} is: {2}", baseNumber, exponent, Power(baseNumber, exponent));
}
}