/* * Simple example of loop -- loop version of fibonacci.c */ #include int fib(int n); int main(void) { int n; printf("enter integer value\n"); if (scanf("%d", &n) == 1) { printf("fibonacci(%d) is %d\n", n, fib(n)); return 0; } else { printf("not an integer value\n"); return 1; } } int fib(int n) { if (n <= 1) return 1; int current; int prev = 1; int prevprev = 1; for (int index = 2; index <= n; ++index) { /* * at this point: * prev == fib(index-1) * prevprev == fib(index-2) */ current = prevprev + prev; /* * now current == fib(index) */ prevprev = prev; prev = current; } return current; /* * sample trace of execution of "for" loop, with n == 4 * * at start of first iteration: * index = 2 * prevprev = 1 * prev = 1 * at end of iteration: * current = 2 (note that this is fib(2)) * prevprev = 1 * prev = 2 * * at start of next iteration: * index = 3 * prevprev = 1 * prev = 2 * at end of iteration: * current = 3 (note that this is fib(3)) * prevprev = 2 * prev = 3 * * at start of next iteration: * index = 4 * prevprev = 2 * prev = 3 * at end of iteration: * current = 5 (note that this is fib(4)) * prevprev = 3 * prev = 5 * * loop stops because index becomes 5, which is not <= 4 */ }