The source code to implement Power() method using recursion is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# Program to implement Power() method using recursion.
using System;
class Recursion
{
public static int Power(int number, int power)
{
if (power == 0)
{
return 1;
}
else
{
return number*Power(number,power-1);
}
}
public static void Main()
{
int num = 0;
int pow = 0;
int result = 0;
Console.Write("Enter the number: ");
num = int.Parse(Console.ReadLine());
Console.Write("Enter the power: ");
pow = int.Parse(Console.ReadLine());
result = Power(num, pow);
Console.WriteLine("Result : "+result);
}
}
Output:
Enter the number: 4
Enter the power: 3
Result : 64
Press any key to continue . . .
Explanation:
In the above program, we created a Recursion class. The Recursion class contains two static methods Main() and Power().
The Power() is a recursive method, here we calculated the power of a specified number. Here every recursive call decreases the value of power and we multiply the result of recursive call with the number. The method gets terminated when the value of power reaches the 0.
In the Main() method, we read the value of number and power and then calculate the power using the recursive method Power() and then print the result on the console screen.
Program:
The source code to implement Power() method using recursion is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
Output:
Explanation:
In the above program, we created a Recursion class. The Recursion class contains two static methods Main() and Power().
The Power() is a recursive method, here we calculated the power of a specified number. Here every recursive call decreases the value of power and we multiply the result of recursive call with the number. The method gets terminated when the value of power reaches the 0.
In the Main() method, we read the value of number and power and then calculate the power using the recursive method Power() and then print the result on the console screen.