C++ Program to Calculate Power Using Recursion

C++ProgrammingServer Side Programming

The power of a number can be calculated as x^y where x is the number and y is its power.

For example.

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

A program to find the power using recursion is as follows.

Example

 Live Demo

#include <iostream>
using namespace std;
int FindPower(int base, int power) {
   if (power == 0)
   return 1;
   else
   return (base * FindPower(base, power-1));
}
int main() {
   int base = 3, power = 5;
   cout<<base<<" raised to the power "<<power<<" is "<<FindPower(base, power);
   return 0;
}

Output

3 raised to the power 5 is 243

In the above program, the function findPower() 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.

int FindPower(int base, int power) {
   if (power == 0)
   return 1;
   else
   return (base * findPower(base, power-1));
}

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

This can be seen in the below code snippet.

3 raised to the power 5 is 243
raja
Published on 27-Sep-2018 13:05:58
Advertisements