/* * Program to compute elements of the Fibonacci sequence using loop. * * (more efficient than recursion, but also a little harder to write and * understand?) */ #include int fibonacci(int n); int main(void) { int n; printf("enter n\n"); if (scanf("%d", &n) != 1) { printf("not number\n"); return 1; } if (n < 0) { printf("negative\n"); return 1; } printf("fibonacci(%d) is %d\n", n, fibonacci(n)); return 0; } int fibonacci(int n) { /* * for n == 0, 1 * for n == 1, 1 * otherwise fibonacci(n-1) + fibonacci(n-2) */ if (n <= 1) { return 1; } else { /* * i is main loop variable * one_before is fibonacci(i-1) * two_before is fibonacci(i-2) */ int i = 2; int one_before = 1; int two_before = 1; int current; for ( ; i <= n; ++i) { current = one_before + two_before; two_before = one_before; one_before = current; } return current; } }