Surviving the Technical Interview
Dr. Dobb's Journal Fall 1998
By Jay Sutaria
<b>(a)</b> int iterative_fibonacci (int number) { int fib_n = 0; int fib_n_plus_1 = 1; int rval = 1; int i; if (number < 0) { /* we'll return -1 if there's an error */ return (-1); } else { for (i = 0; i < number; i++) { rval = fib_n + fib_n_plus_1; fib_n = fib_n_plus_1; fib_n_plus_1 = rval; } return (rval); } } <b>(b)</b> int recursive_fibonacci_one (int number) { if (number < 0) { /* we'll return -1 if there's an error */ return (-1); } else if (number == 0) { return (0); } else if (number == 1) { return (1); } else { return (recursive_fibonacci_one (number-1) + recursive_fibonacci_one (number-2)); } }
Example 2: Computing the nth number in the Fibonacci sequence: (a) iterative; (b) recursive.
Copyright © 1998, Dr. Dobb's Journal