C# program to calculate Power of a number using recursion
Here's a C# program that calculates the power of a number using recursion:
using System;
class Program
{
static void Main()
{
int number = 3;
int exponent = 4;
long result = CalculatePower(number, exponent);
Console.WriteLine(number + " raised to the power of " + exponent + " is: " + result);
}
static long CalculatePower(int number, int exponent)
{
// Base case: if the exponent is 0, return 1
if (exponent == 0)
{
return 1;
}
else
{
// Recursive case: calculate the power by multiplying the number
// with the power of (number, exponent - 1)
return number * CalculatePower(number, exponent - 1);
}
}
}
In this program, we have the CalculatePower method that takes an integer number as the base and an integer exponent as the power and returns the result of number raised to the power of exponent.
We have a base case where if the exponent is 0, we return 1, as any number raised to the power of 0 is 1.
In the recursive case, we calculate the power by multiplying number with the power of (number, exponent - 1). We make a recursive call to CalculatePower with the same number and (exponent - 1).
The recursive calls continue until we reach the base case (exponent equals 0), at which point the recursion stops and the power is calculated.
In the example above, the output would be:
3 raised to the power of 4 is: 81
The power of 3 raised to 4 is calculated as 3 * 3 * 3 * 3, which equals 81.