C++ Program to Calculate Power Using Recursion
int power(int base, int exp) { if (exp == 0) return 1; return base * power(base, exp - 1); } which multiplies the base by itself exp times recursively.Examples
How to Think About It
Algorithm
Code
#include <iostream> using namespace std; int power(int base, int exp) { if (exp == 0) return 1; return base * power(base, exp - 1); } int main() { int base = 2, exponent = 3; cout << "Power: " << power(base, exponent) << endl; return 0; }
Dry Run
Let's trace power(2, 3) through the code
Initial call
power(2, 3) checks if exponent == 0 (false), returns 2 * power(2, 2)
Second call
power(2, 2) checks if exponent == 0 (false), returns 2 * power(2, 1)
Third call
power(2, 1) checks if exponent == 0 (false), 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 function stops recursion when the exponent is zero by returning 1, because any number raised to the power 0 is 1.
Step 2: Recursive Call
For exponents greater than zero, the function calls itself with the exponent decreased by one, multiplying the base each time.
Step 3: Multiplying Results
Each recursive call multiplies the base by the result of the smaller exponent, building up the final power value.
Alternative Approaches
#include <iostream> using namespace std; int power(int base, int exp) { int result = 1; for (int i = 0; i < exp; i++) { result *= base; } return result; } int main() { cout << "Power: " << power(2, 3) << endl; return 0; }
#include <iostream> using namespace std; int power(int base, int exp) { if (exp == 0) return 1; int half = power(base, exp / 2); if (exp % 2 == 0) return half * half; else return base * half * half; } int main() { cout << "Power: " << power(2, 10) << endl; return 0; }
Complexity: O(n) time, O(n) space
Time Complexity
The function calls itself once per decrement of the exponent, so it runs in linear time proportional to 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?
Fast exponentiation reduces time to O(log n) by dividing the problem, making it faster than simple recursion or loops for large exponents.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple Recursion | O(n) | O(n) | Small exponents, easy to understand |
| Loop Iteration | O(n) | O(1) | Simple and memory efficient |
| Fast Exponentiation | O(log n) | O(log n) | Large exponents, performance critical |