C# Program to Calculate Power Using Recursion
Power(int baseNum, int exponent) that calls itself with exponent - 1 until it reaches zero, returning 1 as the base case.Examples
How to Think About It
Algorithm
Code
using System; class Program { static int Power(int baseNum, int exponent) { if (exponent == 0) return 1; return baseNum * Power(baseNum, exponent - 1); } static void Main() { Console.WriteLine(Power(2, 3)); } }
Dry Run
Let's trace Power(2, 3) through the code
Initial call
Power(2, 3) checks if exponent == 0 (false), so returns 2 * Power(2, 2)
Second call
Power(2, 2) checks if exponent == 0 (false), so returns 2 * Power(2, 1)
Third call
Power(2, 1) checks if exponent == 0 (false), so returns 2 * Power(2, 0)
Base case
Power(2, 0) returns 1 because exponent == 0
Return values
Power(2, 1) returns 2 * 1 = 2 Power(2, 2) returns 2 * 2 = 4 Power(2, 3) returns 2 * 4 = 8
| Call | Exponent | Return Value |
|---|---|---|
| Power(2, 0) | 0 | 1 |
| Power(2, 1) | 1 | 2 |
| Power(2, 2) | 2 | 4 |
| Power(2, 3) | 3 | 8 |
Why This Works
Step 1: Base Case
The recursion stops when exponent == 0, returning 1 because any number to the power zero is 1.
Step 2: Recursive Call
For other cases, the function calls itself with exponent - 1, reducing the problem size.
Step 3: Multiplication
Each recursive call multiplies the base number by the result of the smaller problem, building up the final power value.
Alternative Approaches
using System; class Program { static int PowerLoop(int baseNum, int exponent) { int result = 1; for (int i = 0; i < exponent; i++) { result *= baseNum; } return result; } static void Main() { Console.WriteLine(PowerLoop(2, 3)); } }
using System; class Program { static void Main() { double result = Math.Pow(2, 3); Console.WriteLine((int)result); } }
Complexity: O(n) time, O(n) space
Time Complexity
The function calls itself exponent times, so the time grows linearly with the exponent.
Space Complexity
Each recursive call adds a new layer to the call stack, so space used is proportional to the exponent.
Which Approach is Fastest?
The iterative loop approach is faster and uses less memory than recursion because it avoids call stack overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursion | O(n) | O(n) | Simple code, small exponents |
| Loop | O(n) | O(1) | Better performance, large exponents |
| Math.Pow | O(1) | O(1) | Built-in, optimized, floating-point |