Program To Calculate Number Power Using Recursion In C++. The power number should always be positive integer.
Sure! Here is an example program in C++ that calculates the power of a number using recursion:
#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 number: ";
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
andexponent
. It calculates the power ofbase
raised to theexponent
using recursion.Inside the
power
function, there is a base case that checks if theexponent
is equal to 0. If it is, the function returns 1, as any number raised to the power of 0 is 1.If the base case is not met, the function recursively calls itself with the
exponent
decremented by 1. This recursive call multiplies thebase
with the result of the recursive call.In the
main
function, the user is prompted to enter thebase
andexponent
values.The
power
function is then called with the providedbase
andexponent
values, and the result is stored in theresult
variable.Finally, the result is printed to the console along with the original
base
andexponent
values.
This program uses recursion to calculate the power of a number by repeatedly multiplying the base number with itself, reducing the exponent by 1 each time until the exponent becomes 0.