This program takes two integers from user ( base number and a exponent) and calculates the power. Instead of using loops to calculate power, this program uses recursion to calculate the power of a number.
Source code to calculate power using recursion
/* Source Code to calculate power using recursive function */
#include <iostream>
using namespace std;
int power(int n1,int n2);
int main()
{
int base, exp;
cout << "Enter base number: ";
cin >> base;
cout << "Enter power number(positive integer): ";
cin >> exp;
cout << base << " ^ " << exp << " = " << power(base, exp);
return 0;
}
int power(int base,int exp)
{
if ( exp!=1 )
return (base*power(base,exp-1));
}
Output
Enter base number: 3
Enter power number(positive integer): 3
3^3 = 27
This program can only calculate the power if base power and exponent are integers.