/* * Program demonstrating use of recursion to compute Fibonacci * numbers. (This is actually an incredibly inefficient way to * compute them, but pretty, and a good example of recursion.) * * Input: a non-negative integer n. * * Output: the n-th Fibonacci number. */ #include /* Compute n-th fibonacci number and return it */ int fib(int n) { /* base case -- 0th and 1st numbers are 1 */ if (n <= 1) { return 1; } /* for n > 1, n-th number is sum of previous two */ else { return fib(n-1) + fib(n-2); } } /* Main program */ int main(void) { int n; printf("enter a non-negative integer\n"); if (scanf("%d", &n) != 1) { printf("error: not an integer\n"); } else if (n < 0) { printf("error: negative\n"); } else { printf("the %d-th Fibonacci number is %d\n", n, fib(n)); } return 0; }