//Chapter 19 programming challenge 6
//Recursive Power Function
//
#include <iostream>
usingnamespace std;
//function prototype
int power(int, int);
int main()
{
int base, exponent, product;
//Ask user to input base number and exponent
cout << " Please first enter the base and then the exponent. " << endl;
cin >> base >> exponent;
product = power(base, exponent);
cout << " The solution to your power is: " << product << endl;
return 0;
//***************************************************************************
//power to recursively determine the product of the power *
//***************************************************************************
int power(int number, int exponent)
{
if (exponent == 1) //base case
return number;
elseif (exponent > -1)
exponent--;
return number* (power(number, exponent));
}
}
Try running with base=10 and exponent=0. What should the answer be? What answer do you get?
Also, what about negative exponents? Hmm. The answer would a fraction, but you can't return that. A handy way to solve this is to change exponent to unsignedint so it's impossible to pass a negative exponent. Just be sure to change the code that compares it to -1!