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);
}
}
}
Code Explanation
1. The Program Structure
The program starts with the using System;
statement, which allows the program to use basic functionalities like Console.WriteLine
for printing output to the console.
The Program
class contains the Main
method, which is the entry point of the program. This is where the program starts executing.
2. The Main Method
Inside the Main
method:
3. The CalculatePower Method
This method is responsible for calculating the power of a number using recursion (a function calling itself).
It takes two parameters:
number
: The base number.
exponent
: The power to which the number is raised.
The method has two cases:
- Base Case:
- If the
exponent
is 0
, the method returns 1
. This is because any number raised to the power of 0 is 1 (e.g., \(3^0 = 1\)).
- This is the stopping condition for the recursion, preventing it from running indefinitely.
- Recursive Case:
- If the
exponent
is greater than 0, the method calls itself with the same number
but with the exponent
reduced by 1 (exponent - 1
).
- The result of this recursive call is multiplied by the
number
and returned.
- For example:
- If
number = 3
and exponent = 4
, the method calculates:
3 * CalculatePower(3, 3)
4. How the Recursion Works
Let's trace the recursion for number = 3
and exponent = 4
:
CalculatePower(3, 4)
calls 3 * CalculatePower(3, 3)
.
CalculatePower(3, 3)
calls 3 * CalculatePower(3, 2)
.
CalculatePower(3, 2)
calls 3 * CalculatePower(3, 1)
.
CalculatePower(3, 1)
calls 3 * CalculatePower(3, 0)
.
CalculatePower(3, 0)
returns 1
(base case).
- Now, the recursion "unwinds":
CalculatePower(3, 1)
returns 3 * 1 = 3
.
CalculatePower(3, 2)
returns 3 * 3 = 9
.
CalculatePower(3, 3)
returns 3 * 9 = 27
.
CalculatePower(3, 4)
returns 3 * 27 = 81
.
The final result, 81
, is returned to the Main
method and printed.
5. Summary
The program calculates \(3^4\) using recursion.
The CalculatePower
method breaks down the problem into smaller subproblems by reducing the exponent step by step until it reaches the base case.
The result is computed by multiplying the number with the result of the recursive call.
The final output is:
3 raised to the power of 4 is: 81
This is a classic example of how recursion can be used to solve problems by breaking them into smaller, more manageable parts.