public class Fibonacci5 { public static void main (String[] argv) { // Test case 1: int n = 5; int f = fibonacci (n); System.out.println ("f(" + n + ") = " + f); // Test case 2: n = 20; f = fibonacci (n); System.out.println ("f(" + n + ") = " + f); } static int fibonacci (int n) { // Base cases: same as in recursive version. if (n == 1) { return 0; } else if (n == 2) { return 1; } // Now we know n >= 3. // Start with first and second terms. int fPrev = 1; int fPrevPrev = 0; int f = -1; // A simple iteration takes us to the n-th term. for (int k=3; k<=n; k++) { f = fPrev + fPrevPrev; fPrevPrev = fPrev; fPrev = f; } return f; } }