//Example code showing how a factorial calculation might be implemented using //recursion. #include <iostream> using namespace std; //Function prototype double factorial(long long n); //MAIN LOOP - Very simple and hopefully self explanatory. main() { cout << "Input number: "; long int value_in; cin >> value_in; //Note that value_in is a long int, but factorial() is expecting a //long long. Is this okay? What limitations or side effects might result? cout << value_in << "! = " << factorial(value_in) << endl; } //Factorial function definition - use cautiously! Play around to see what //input values this function actually works for and which cause it to break //down. // //Try changing the return value here (and in the prototype above) to other //variable types (e.g., unsigned long long, unsigned int, etc.) and see how //the results are affected. double factorial(long long n) { //Since we allow a signed input, we must check for this potential error if (n < 0) { cout << "ERROR! Input was negative!" << endl; exit(1); } double value = 0; //Base cases: if (n == 0) value = 1; if (n == 1) value = 1; //Otherwise, recurse: else value = n * factorial(n - 1); return value; }