// test_factorial.cpp the simplest example of a recursive function // a recursive function is a function that calls itself static int factorial(int n) // n! is n factorial = 1*2*3*...*(n-1)*n { if( n <= 1 ) return 1; // must have a way to stop recursion return n * factorial(n-1); // factorial calls factorial with n-1 } // n * (n-1) * (n-2) * ... * (1) #include using namespace std; int main() { cout << " 0!=" << factorial(0) << endl; // Yes, 0! is one cout << " 1!=" << factorial(1) << endl; cout << " 2!=" << factorial(2) << endl; cout << " 3!=" << factorial(3) << endl; cout << " 4!=" << factorial(4) << endl; cout << " 5!=" << factorial(5) << endl; cout << " 6!=" << factorial(6) << endl; cout << " 7!=" << factorial(7) << endl; cout << " 8!=" << factorial(8) << endl; cout << " 9!=" << factorial(9) << endl; cout << "10!=" << factorial(10) << endl; cout << "11!=" << factorial(11) << endl; cout << "12!=" << factorial(12) << endl; cout << "13!=" << factorial(13) << endl; cout << "14!=" << factorial(14) << endl; cout << "15!=" << factorial(15) << endl; // expect a problem with cout << "16!=" << factorial(16) << endl; // integer overflow cout << "17!=" << factorial(17) << endl; // uncaught in C++ (Bad!) cout << "18!=" << factorial(18) << endl; return 0; } // output of execution is: // 0!=1 // 1!=1 // 2!=2 // 3!=6 // 4!=24 // 5!=120 // 6!=720 // 7!=5040 // 8!=40320 // 9!=362880 // 10!=3628800 // 11!=39916800 // 12!=479001600 // 13!=1932053504 // wrong! 13! = 12! * 13, must end in two zeros // 14!=1278945280 // wrong! and no indication! // 15!=2004310016 // wrong! // 16!=2004189184 // wrong! // 17!=-288522240 // wrong and obvious if you check your results // 18!=-898433024 // Only sometimes does integer overflow go negative