Exercise:
Write a C++ program that uses recursive functions to calculate power.
Click Here to View the Solution:
#include <iostream>
using namespace std;
int power(int, int);
int main()
{
int num, p, ans;
cout << "Insert a positive number: ";
cin >> num;
cout << "Insert the power of the number: ";
cin >> p;
ans = power(num, p);
// pow(num,p) is a pre-defined function available in C++
cout << num << "^" << p << " = " << ans;
return 0;
}
int power(int num, int p)
{
if (p != 0)
return (num*power(num, p-1));
else
return 1;
}
Click Here to View the Output:
Insert a positive number: 3 Insert the power of the number: 4 3^4 = 81
Click Here to View the Explanation:
- User is requested to enter a positive integer. It is stored as a variable
num
. The user is requested to enter the power and it is saved asp
. - The
pow ()
function is used calculate the power ofnum
and the answer is stored in a variable asans
. - A recursive function
power ( )
is created. - The recursive function is called in the
main ()
function. - Output is displayed on the screen.