recursive power in c++
To calculate the power of a number using recursion in C++, you can use the following code:
#include <iostream>
int power(int base, int exponent) {
if (exponent == 0) {
return 1;
} else {
return base * power(base, exponent - 1);
}
}
int main() {
int base, exponent;
std::cout << "Enter the base: ";
std::cin >> base;
std::cout << "Enter the exponent: ";
std::cin >> exponent;
int result = power(base, exponent);
std::cout << base << " raised to the power of " << exponent << " is " << result << std::endl;
return 0;
}
Explanation:
The power
function takes two parameters: base
and exponent
. It calculates the power of base
raised to the exponent
using recursion.
In the power
function, there is a base case and a recursive case.
- The base case is when the exponent is 0. In this case, the function returns 1 because any number raised to the power of 0 is 1.
- The recursive case is when the exponent is not 0. In this case, the function recursively calls itself with the same base
and exponent - 1
, and multiplies the base
with the result of the recursive call.
In the main
function, the user is prompted to enter the base
and exponent
values. The power
function is then called with these values, and the result is printed.
This recursive approach gradually reduces the exponent by 1 in each recursive call until it reaches the base case, at which point the function starts returning the calculated result back up the recursive chain.
The code is enclosed in a main
function, which is the entry point of the program. After calculating the power, the result is printed to the console.
I hope this explanation helps! Let me know if you have any further questions.