Write a recursive function that calculates the value of a nu

Write a recursive function that calculates the value of a number (“base”) raised to a power (“power”). Assume that power is a nonnegative integer. Document your program.

Solution

Power.cpp

#include <iostream>

using namespace std;
int getPower(int b, int p);
int main()
{
int base, power;
cout << \"Enter base: \";
cin >> base;
cout<<\"Enter power: \";
cin >> power;
int result= getPower(base, power);
cout<<\"Result is \"<<result<<endl;
return 0;
}

int getPower(int b, int p)
{
if (p > 0)
return (b*getPower(b, p-1));
else
return 1;
}

Output:

sh-4.3$ g++ -std=c++11 -o main *.cpp                                                                                                                                                                                            

sh-4.3$ main                                                                                                                                                                                                                    

Enter base: 2                                                                                                                                                                                                                   

Enter power: 5                                                                                                                                                                                                                  

Result is 32

Write a recursive function that calculates the value of a number (“base”) raised to a power (“power”). Assume that power is a nonnegative integer. Document your

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site