C Programming

RECURSION
This is where a function repeatedly calls itself to perform calculations. Typical applications are games and Sorting trees and lists.

Consider the calculation of 6! ( 6 factorial )

 ie 6! = 6 * 5 * 4 * 3 * 2 * 1
    6! = 6 * 5!
    6! = 6 * ( 6 - 1 )!
    n! = n * ( n - 1 )!
	/* bad example for demonstrating recursion */
	#include <stdio.h>

	long int factorial( long int );         /* ANSI function prototype */

	long int  factorial( long int n )
	{
		long int result;
		
		if( n == 0L )
			result = 1L;
		else
			result = n * factorial( n - 1L );
		return ( result );
	}

	main()
	{
		int j;
		
		for( j = 0; j < 11; ++j )
			printf("%2d! = %ld\n", factorial( (long) j) );
	}


EXERCISE C19
Rewrite example c9 using a recursive function.

Answer


©Copyright B Brown. 1984-1999. All rights reserved.