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:

  1. The power function takes two parameters: base and exponent. It calculates the power of base raised to the exponent using recursion.

  2. Inside the power function, there is a base case that checks if the exponent is equal to 0. If it is, the function returns 1, as any number raised to the power of 0 is 1.

  3. If the base case is not met, the function recursively calls itself with the exponent decremented by 1. This recursive call multiplies the base with the result of the recursive call.

  4. In the main function, the user is prompted to enter the base and exponent values.

  5. The power function is then called with the provided base and exponent values, and the result is stored in the result variable.

  6. Finally, the result is printed to the console along with the original base and exponent 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.