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 5^{4} 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,

- n
^{P}= n * n * n ….. P times - n
^{P}= n * n^{P-1}

For example, in the first, we calculate the n^{P} by multiplying **n ,** **p **times like this for example

5^{4} =5 * 5 * 5 * 5 that is a simple approach, and in the second, we calculate n^{p-1} and multiply it with n to get n^{p}.

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 **n ^{0} = 1**, as

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.

Submitted by Rahul Chandrakant Suthar (Rahulcs27)

Download packets of source code on Coders Packet

## Comments