Power of a number in C++ using Recursion

In this tutorial, we are going to learn how to calculate power of a number in C++ using Recursion. In recursion, we need a required recursive function to solve this problem. The following recursive function will call itself again and again until the base case is reached and we will get our required answer.

Let us understand by taking an example:

We will have our recursive function like this:

F(a,b) =a* F(a,b-1)

and we will have a base case when b=0; we will return 1.

where a denotes the number and b denotes exponent.




Suppose we have to calculate 2 to the power 2, which we know equals to 4 but how recursion will be able to solve this problem.

It will work like this:

F(2,2)=2*F(2,1)

Again it will call itself,

F(2,1)=2*F(2,0)

Now the base case is reached as b=0, it will return 1, then

F(2,1)=2*1=2

and F(2,2)=2*2=4, which is our required answer.

Let us implement the above idea in our code.

Program to calculate power of a number in C++ using Recursion

Cpp source code:

// Power of a number in C++ using Recursion
#include<bits/stdc++.h>
using namespace std;

// Recursive function
int recu_power(int n,int m)
{
  if(m==0) // base case
  {
    return 1;
  }
  else
  {
    return n*recu_power(n,m-1);
  }
}

// Driver code
int main()
{
  int n,m;
  cout<<"Enter number: ";
  cin>>n;
  cout<<"\nEnter the exponent: ";
  cin>>m;
  cout<<"\n"<<n<<" to the power "<<m <<" is "<<recu_power(n,m)<<"\n";
  return 0;
}

Input/Output:

Enter number: 2

Enter the exponent: 6

2 to the power 6 is 64

You can also learn:

Recursively find first occurrence of a number in a list using Python

Coin change problem in C++

Do not forget to comment if you find anything wrong in the post or you want to share some information regarding the same.


Leave a Reply

Your email address will not be published. Required fields are marked *