UMBC CS 201, Fall 05
UMBC CMSC 201 Fall '05
CSEE | 201 | 201 F'05 | lectures | news | help

fib2

A recursive function for fibonacci with indented tracing.

fib2.c

/* File: fib2.c * Author: Richard Chang * Date: < 12/3/97 * Modified by Sue Evans - 10/30/03 * Section: 101 * EMail: bogar@cs.umbc.edu * * A recursive function for fibonacci with * indented tracing. */ #include <stdio.h> int Fib (int n, int depth); void Indent (int depth); int main() { int n = -1; while (n < 1) { printf("Enter a positive integer: ") ; scanf ("%d", &n); } Fib (n, 0) ; return 0; } /*********************************** * Fib recursively traces the fibonacci sequence * for the nth number in the sequence * Input: the number-place in the sequence to find and * the current depth of recursion * Output: the value of the nth number in the sequence * * Side Effect: prints tracing to find the number ***********************************/ int Fib (int n, int depth) { int result; Indent (depth); printf("fib(%d)\n", n); if (n < 2) { result=1; } else { result = Fib(n - 1, depth + 1) + Fib(n - 2, depth + 1); } Indent (depth); printf("%d\n", result); return (result); } /**************************** * Indent prints vertical lines for the depth of * recursion in a recursive function to be traced * * Input: depth, will be the number of lines * Output: [depth] printed lines, no return value ****************************/ void Indent (int depth) { int i; for (i = 0; i < depth; i++) { printf("| "); } }

Output

Enter a positive integer: 4 fib(4) | fib(3) | | fib(2) | | | fib(1) | | | 1 | | | fib(0) | | | 1 | | 2 | | fib(1) | | 1 | 3 | fib(2) | | fib(1) | | 1 | | fib(0) | | 1 | 2 5


CSEE | 201 | 201 F'05 | lectures | news | help

Last Modified - Tuesday, 27-Sep-2005 00:29:20 EDT