nfact.c

/*
 * NFACT -- compute a factorial recursively
 *
 * Usage: nfact 
 *      
 * Inputs: integer n
 * Outputs: n! = f
 * Errors: n < 0
 *
 * Assumptions: - the arguments are not digits followed by non-digits
 *                (unchecked)
 *              - n >= 0 (checked)
 *      
 * Matt Bishop, ECS 36A
 * * October 17, 2019 -- wrote original version
 */             
#include <stdio.h>      
                        
/*              
 * NFACT -- compute the factorial 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 ro
 */
int main(void)
{
	int rv;			/* success of failure of read */
	int ch;			/* character to discard */
	int n;			/* number to compute the factorial of */
	int badct = 0;		/* number of bad arguments */

	/*
	 * loop through the argument list
	 */
	printf("> ");
	while((rv = scanf("%d", &n)) != EOF){
		if (rv != 1){
			fprintf(stderr, "Invalid input\n");
			/* discard the rest of the line */
			while((ch = getchar()) != '\n' && ch != EOF)
				;
			/* quit on EOF; loop on error */
			if (ch == EOF)
				return(badct);
			badct++;
			printf("> ");
			continue;
		}
		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));
		printf("> ");
	}

	/*
	 * return exit code of the number of failures
	 */
	return(badct);
}


UC Davis sigil
Matt Bishop
Office: 2209 Watershed Sciences
Phone: +1 (530) 752-8060
Email: [email protected]
ECS 36A, Programming & Problem Solving
Version of April 2, 2024 at 12:13PM

You can get the raw source code here.

Valid HTML 4.01 Transitional Built with BBEdit Built on a Macintosh