//------------------------------------------------------------------------------ // A simple recursive C programme. Is it *reentrant*? #include #include #define TRUE (0 == 0) // In C, "#define" is a -text- substitution #define FALSE (0 == 1) // These statements say what they mean int factorial(int x); // Function declaration (for later forward reference) int error; // Global variable // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - main (int argc, char *argv[]) { int i, j; if (argc < 2) printf("Needs a parameter.\n"); else { error = FALSE; // This is set if the integer range is exceeded i = atoi(argv[1]); // Convert the argument string to an integer if (i < 0) printf("Positive numbers only, please.\n"); else { if (i == 0) j = factorial(1); // 0! is same as 1! else j = factorial(i); // First call if (!error) printf("The factorial of %d is %d.\n", i, j); else printf("Sorry, factorial %d overflowed.\n", i); } } exit(0); } //------------------------------------------------------------------------------ // Recursive factorial evaluation. int factorial(int x) { int k; if (x == 1) return 1; else { k = x * factorial(x-1); // Recursive call if (k < 0) error = TRUE; // Exceeding the number range will make return k; // the value appear negative (at first). } } //------------------------------------------------------------------------------ // // Factorial evaluation is often used as an -example- of recursion; it is // not the most efficient way to do this in most cases. // //------------------------------------------------------------------------------