Skip to content
Home » Blog » C++ Program to Calculate Power Using Recursion

C++ Program to Calculate Power Using Recursion

Calculate Power Using Recursion

In this Program, you’ll learn how to Calculate Power Using Recursion in C++ Programming along with that you’ll learn how the functions used in this program.

Now let’s understand how to find the recursion manually, below is the formula to do this manually and we have to implement this in the program.

Let’s say, x = 2 and y = 10
x^y =1024
Here, x^y is 2^10

now we’ll do the same with this program

Program to Calculate Power Using Recursion

#include  
using namespace std;
 
//function declaration
double Power(double base, int exponent);
 
int main()
{
    double base, power;
    int exponent;
 
    // Inputting base and exponent from user
    cout<<"Enter base: "; cin>>base;
    cout<<"Enter exponent: "; cin>>exponent;
 
    // Call Power function
    power = Power(base, exponent);
 
    //printf("%.2lf ^ %d = %f", base, exponent, power);
    cout<<base<< "^"<<exponent<<" = "<<power;
 
    return 0;
}
 
/*
  Calculating power of any number.
  Returns base ^ exponent
 */
double Power(double base, int exponent)
{
    // Base condition
    if(exponent == 0)
        return 1;
    else if(exponent > 0)
        return base * pow(base, exponent - 1);
    else
        return 1 / pow(base, - exponent);
}

Output

Enter base: 5
Enter exponent: 3
5^3 = 125

In the above program, the function pow() is a recursive function. If the power is zero, then the function returns 1 because any number raised to power 0 is 1. If the power is not 0, then the function recursively calls itself. This is demonstrated using the following code snippet.

In the main() function, the pow() function is called initially and the power of a number is displayed.

Related Programs

Ask your questions and clarify your/others doubts on how to Calculate Power Using Recursion by commenting. Documentation

Please write to us at [email protected] to contribute or to report an issue with the above content or for feedback.