/* Faan Tone Liu Jan 28, 2003 Demo program for cmp 1672 Shows a recursive function: calculate integer powers */ #include using namespace std; // prototype for our recursive function that calculates integer powers int integer_power(int b, int e); int main() { int base(-1), exponent(-1); cout << "This program calculates integer powers." << endl; cout << "Input the base and exponent: "; cin >> base >> exponent; while (exponent < 0) { cout << "The exponent must be non-negative."; cout << "Input the base and exponent: "; cin >> base >> exponent; } cout << base << " to the " << exponent << " power = " << integer_power(base, exponent) << endl; return 0; } // recursive function to calculate integer powers - returns b^e // base case: When the exponent is 0 or 1, then the answer is easy, just // return it. When exponent==0, the answer is 1, when exponent==1, the // answer is just the base. // recursive step: b^e = b*b^(e-1) int integer_power(int b, int e) { if (e == 0) return 1; if (e == 1) return b; return b*integer_power(b, e-1); }