Lecture #6: Recursion

Reading: Holmes, Chapter 12
Handouts: Factorial
  1. Greetings and felicitations
  2. What is recursion?
    1. math: think induction
    2. factorial: n! = n * (n-1)!, 0! = 1
  3. Program stack
    1. where arguments, locals, return addresses, state variables go
    2. walk through 3! to show how to use it
  4. Equivalent to iteration
    1. show factorial; equivalence can be proven mathematically
  5. Thinking about it
    1. if you can change probem to a simpler case, you got it
    2. need a terminal case
  6. String length
    1. break it down
    2. show solution

Factorial

This prompts you for an integer and prints the factorial. It does not check for overflow!
/*
 * program to compute a factorial
 * invocation:
 *	fact		run it
 * exit code: 0 always
 * author: Matt Bishop, [email protected], 9/16/96
 */
#include <stdio.h>
#include <stdlib.h>

/*
 * compute a single-precision factorial
 */
int fact(int n)
{
	if (n < 0)	return(-1);	/* sanity check */
	if (n == 0)	return(1);	/* terminal case */
	return(n * fact(n-1));	/* recurse */
}

/*
 * the main program
 */
int main(void)
{
	int n;			/* number to compute factorial of */
	register int nread;		/* number of numbers read */

	/*
	 * read numbers and compute their factorial
	 */
	while(printf("> "), (nread = scanf("%d", &n)) != EOF){
		switch(nread){
		case 0:		/* bad input */
			printf("Need a non-negative integer\n");
			break;
		case 1:		/* good input */
			printf("\t%d\n", fact(n));
			break;
		default:	/* can't happen (uh huh ...) */
			printf("HUH? nread = %d?!?!\n", nread);
			break;
		}
	}

	/*
	 * skip to a new line and quit
	 */
	putchar('\n');
	return(EXIT_SUCCESS);
}

You can also see this document as a RTF document, a Postscript document, or a plain ASCII text document.
Send email to [email protected].

Department of Computer Science
University of California at Davis
Davis, CA 95616-8562



Page last modified on 10/18/97