UMBC CS 201, Fall 98
UMBC CMSC 201 & 201H Fall '98 CSEE | 201 | 201 F'98 | lectures | news | help

fib2

A recursive function for fibonacci with indented tracing.

fib2.c

/* File: fib2.c * * A recursive function for fibonacci with * indented tracing. */ #include <stdio.h> int Fib (int n, int depth); void Indent (int depth); main() { int n = -1; while (n < 1) { printf("Enter a positive integer: ") ; scanf ("%d", &n); } Fib (n, 0) ; } 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); } void Indent (int depth) { int i; for (i = 0; i < depth; i++) { printf("| "); } }

Output

% cc201 fib2.c % a.out 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'98 | lectures | news | help

Sunday, 06-Dec-1998 18:06:27 EST