/******************************************************************/ // R. A. Hillyard // factorial2.cpp // last modified: 02/15/2001 // // program to calcualte a factorial n where n is entered by the user /******************************************************************/ #include<iostream> using namespace std; int main() { bool flag = true; while(flag) { int product = 1; //hold the result int n = 0; //hold user input do{ cout << "enter a positive integer less than 13 (0 to quit): "; cin >> n; //check for valid input //loop while input is out or range if(n > 12 || n < 0) { cout << n << " is invalid try again!\n"; } }while(n>12 || n<0); //if sentinal value - set flag to false to exit loop if(n == 0) flag = false; //input is ok - now compute the factorial else { int j = 1; while(j <= n) { product *= j; j++; } cout << n << " factorial is equal to: " << product << endl; }//end else }//end while flag return 0; }//end main
/******************************************************************/ enter a positive integer less than 13 (0 to quit): 3 3 factorial is equal to: 6 enter a positive integer less than 13 (0 to quit): 4 4 factorial is equal to: 24 enter a positive integer less than 13 (0 to quit): 9 9 factorial is equal to: 362880 enter a positive integer less than 13 (0 to quit): 12 12 factorial is equal to: 479001600 enter a positive integer less than 13 (0 to quit): 16 16 is invalid try again! enter a positive integer less than 13 (0 to quit): 13 13 is invalid try again! enter a positive integer less than 13 (0 to quit): -8 -8 is invalid try again! enter a positive integer less than 13 (0 to quit): 0