Calculate Power Using Recursion
C++
Medium
6 views
Problem Description
Calculate x raised to power n (x^n) using recursive function.
Real Life: Like calculating compound interest repeatedly.
Step-by-Step Logic:
1. Base case: if power is 0, return 1
2. Recursive case: multiply number with power(number, n-1)
3. Function calls itself with reduced power
4. Return final result
Official Solution
int calculatePower(int base, int exponent) {
if(exponent == 0) {
return 1; // Base case
}
return base * calculatePower(base, exponent - 1); // Recursive call
}
void function_q6_power_recursion() {
int x = 2;
int n = 5;
int result = calculatePower(x, n);
cout << x << " raised to power " << n << " is: " << result << endl;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!