fibrec.c

/*
 * Recursive Fibonacci program
 *
 * Matt Bishop, ECS 36A
 *
 * -- May 21, 2024	Original program
 */
#include <stdio.h>

/*
 * the interior, recursive function
 * called by fib, which does error checking
 */
int fibx(int n)
{
	/* BASE CASE: n = 1 or 2, fibonacci number is 1 */
	if (n == 1 || n == 2)
		return(1);

	/* recurse and return the value */
	return(fibx(n-2) + fibx(n-1));
}

/*
 * the interface
 * this does *not* recurse; it checks for errors in n
 * and returns an error code if found
 * otherwise, it calls fibx repeatedly, printing out
 * the fibonacci each step along the way
 *
 * n is numbert of Fibonacci numbers to compute
 */
int fib(int n)
{
	int i;			/* counter in a for loop */

	/* computing negative or no numbers makes no sense */
	if (n <= 0)
		return(0);

	/* loop, printing each fibonacci number as it is comnputed */
	for(i = 1; i <= n; i++)
		printf("%d ", fibx(i));
	putchar('\n');

	/* return success */
	return(1);
}


UC Davis sigil
Matt Bishop
Office: 2209 Watershed Sciences
Phone: +1 (530) 752-8060
Email: mabishop@ucdavis.edu
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