Coders Packet

Using recursion, compute N raised to the power of P in C++

By Rahul Chandrakant Suthar

In this project, we will discuss how to use Recursion in CPP language to compute N raised to the power of P

For example, if we want to calculate 54 it will be 5 * 5 * 5 * 5 which will give us 625.

We can follow these approaches to find the n raised to the power of p,

  1. nP = n * n * n ….. P times
  2. nP = n * nP-1

For example, in the first, we calculate the nP by multiplying n , p times like this for example 

54 =5 * 5 * 5 * 5 that is a simple approach, and in the second, we calculate np-1 and multiply it with n to get np.

 

This is called recursion and means that the function will call itself until an endpoint or break condition is reached.

This calling of Function must now be broken. So we used a Breaking Condition, and the Breaking Condition is n0 = 1, as p is 0 then the answer will be 1

Example of a breaking Condition in C++

if(p==0){
  return 1; // returns 1
}

So to solve this problem we will create a function power in which

If the user sends N and P  then it will call function (n, p-1), So, for example, We will create a function in our code like this

To understand the Logic 

So, if we pass 4 as n and 3 as p to the function,

Now the Execution part.

#include 
using namespace std;
int power(int n,int p){
    if(p==0){
        return 1;
    }
    int prevPower = power(n, p-1);
    return n * prevPower;
}
int main(){
    int n,p;
    cout<<"Enter Number and power"<<endl;
    cin>>n>>p;
    cout<<power(n,p);

    return 0;
}

Input

The number entered by the user is 4 and 3.

Output

Output is 64 as expected.

Download Complete Code

Comments

No comments yet