// This program reads numbers and raises each number to the given power. // The powers are calculated by a function. The program reads numbers // and powers until the user enters zero. #include <iostream.h> // prototype for mypower function long mypower(int num, int exponent); int main() { int num; int exponent; long power; // each iteration of the loop will read a number and an exponent and // raise the number to the exponent by calling the function cout << "Enter a number (enter 0 to end): "; cin >> num; while (num != 0) { cout << "To what power would you like to raise this number: "; cin >> exponent; // call the function to raise the number to the exponent, print result // notice that function call is part of assignment statement power = mypower(num,exponent); cout << "The result of raising " << num << " to the " << exponent; cout << " power is " << power << endl; cout << "Enter a number (enter 0 to end): "; cin >> num; } return 0; } // function definition for mypower // the function mypower raises the first parameter to the power // given by the second parameter long mypower(int num, int exponent) // function header { long result; int i; result = num; for (i = 1 ; i < exponent ; i++) result = result * num; return result; }
Enter a number (enter 0 to end): 2 To what power would you like to raise this number: 16 The result of raising 2 to the 16 power is 65536 Enter a number (enter 0 to end): 10 To what power would you like to raise this number: 3 The result of raising 10 to the 3 power is 1000 Enter a number (enter 0 to end): 5 To what power would you like to raise this number: 4 The result of raising 5 to the 4 power is 625 Enter a number (enter 0 to end): 0
Email Me |
Office Hours |
My Home Page |
Department Home |
MCC Home Page
© Copyright Emmi Schatz 2002