Calculating the Power of a number using recursion involves repeatedly multiplying a base by itself a certain number of times. In C++, you can implement this by defining a recursive function that multiplies the base number until the exponent decreases to zero, which serves as the base case.
Below is a C++ program that calculates the power of a base number raised to an exponent using recursion. This program demonstrates not only the direct recursive approach but also handles negative exponents, which require a little bit of additional logic.
#include <iostream>
// Recursive function to calculate power of a number
double power(double base, int exponent) {
if (exponent == 0) {
// Any number raised to the power of 0 is 1
return 1;
} else if (exponent < 0) {
// Handle negative exponent
return 1 / power(base, -exponent);
} else {
// Recursive case: base * power(base, exponent – 1)
return base * power(base, exponent – 1);
}
}
int main() {
double base;
int exponent;
std::cout << “Enter base: “;
std::cin >> base;
std::cout << “Enter exponent: “;
std::cin >> exponent;
double result = power(base, exponent);
std::cout << base << ” raised to the power of ” << exponent << ” is ” << result << std::endl;
return 0;
}
Explanation:
- Function Definition:
The power function takes two parameters, base (of type double to handle fractional numbers) and exponent (of type int).
- Base Case:
If exponent == 0, the function returns 1, because any number raised to the power of 0 is 1.
-
Handling Negative Exponents:
If the exponent is negative, the function returns the reciprocal of the base raised to the absolute value of the exponent. This is accomplished by 1 / power(base, -exponent).
-
Recursive Case:
If the exponent is positive, the function returns base * power(base, exponent – 1). This expression multiplies the base by the result of the power function called with the exponent decreased by 1, recursively breaking down the problem until it reaches the base case.
-
Input/Output:
The main function handles user input and output, prompting the user to enter the base and exponent, and then it prints the result.
Performance Note
While recursion provides a clear and concise solution for calculating powers, it’s not the most efficient in terms of performance, especially for large exponents. An iterative approach or using the method of exponentiation by squaring (which can also be implemented recursively) would be more efficient, especially for larger numbers, as it reduces the time complexity significantly.