#include #include /* * compute n! recursively */ int fact(int n) { /* error check */ if (n < 0) return(-1); /* base case */ if (n == 0) return(1); /* recursion */ return(n * fact(n-1)); } /* * convert string to int with error checking * no leading signs or magnitude checking */ int cvttoint(char *s) { int n = 0; /* integer being read */ /* skip leading white space */ while(isspace(*s)) s++; /* if it's not a digit, it's not an integer */ if (!isdigit(*s)) return(-1); /* read in the integer */ while(isdigit(*s)) n = n * 10 + *s++ - '0'; /* if it's ended by a NUL, it's an integer */ return(*s ? -1 : n); } int main(int argc, char *argv[]) { int i; /* counter in a for loop */ int n; /* number read in */ int rv = 0; /* exit status code */ /* * do each arg separately */ for(i = 1; i < argc; i++) if ((n = cvttoint(argv[i])) != -1) printf("%d! = %d\n", n, fact(n)); else{ /* error handler*/ rv++; printf("%s: invalid number\n", argv[i]); } /* * bye! */ return(rv); }