/* test_factorial.c 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 int main() { printf(" 0!=%d \n", factorial(0)); /* Yes, 0! is one */ printf(" 1!=%d \n", factorial(1)); printf(" 2!=%d \n", factorial(2)); printf(" 3!=%d \n", factorial(3)); printf(" 4!=%d \n", factorial(4)); printf(" 5!=%d \n", factorial(5)); printf(" 6!=%d \n", factorial(6)); printf(" 7!=%d \n", factorial(7)); printf(" 8!=%d \n", factorial(8)); printf(" 9!=%d \n", factorial(9)); printf("10!=%d \n", factorial(10)); printf("11!=%d \n", factorial(11)); printf("12!=%d \n", factorial(12)); printf("13!=%d \n", factorial(13)); /* expect a problem with */ printf("14!=%d \n", factorial(14)); /* integer overflow */ printf("15!=%d \n", factorial(15)); /* uncaught in C */ printf("16!=%d \n", factorial(16)); printf("17!=%d \n", factorial(17)); /* obvious */ printf("18!=%d \n", factorial(18)); 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 */