/* * NFACT -- compute a factorial recursively * * Usage: nfact n1 n2 ..... * * Inputs: none * Outputs: for each argumenr: n! = f n as above, f is n! * Errors: - ni < 0 * * Assumptions: - the arguments are not digits followed by non-digits * (unchecked) * - ni >= 0 (checked) * * Written by Matt Bishop for ECS 30 * version 1 November 2, 2015 */ #include /* * NFACT -- compute the fqactoriual of n recursively * Parameters: n non-negative integer * Returns: n! * Assumptions: - n is non-negative integer (not checked) * Algorithm: n! = n(n-1)! */ int nfact(int n) { /* base case: 0! = 1 */ if (n == 0) return(1); /* recursive case: n! = n * (n-1)! */ return(n * nfact(n - 1)); } /* * main routine */ int main(int argc, char *argv[]) { int i; /* counter in a for loop */ int n; /* number to compute the factorial of */ int badct = 0; /* number of bad arguments */ /* * loop through the argument list */ for(i = 1; i < argc; i++){ /* translate argument into integer, balk on error */ if (sscanf(argv[i], "%d", &n) != 1){ badct++; fprintf(stderr, "%s: not an integer\n", argv[i]); } else if (n < 0) /* check it is non-negative, balk if not */ fprintf(stderr, "%d: need a non-negative integer\n", n); else /* compute and print the factorial */ printf("%d! = %d\n", n, nfact(n)); } /* * return exit code of the number of failures */ return(badct); }