1  import java.util.Scanner;
  2  
  3  /**
  4     This program computes Fibonacci numbers using an iterative method.
  5  */ 
  6  public class LoopFib
  7  {  
  8     public static void main(String[] args)
  9     {  
 10        Scanner in = new Scanner(System.in);
 11        System.out.print("Enter n: ");
 12        int n = in.nextInt();
 13  
 14        for (int i = 1; i <= n; i++)
 15        {
 16           long f = fib(i);
 17           System.out.println("fib(" + i + ") = " + f);
 18        }
 19     }
 20  
 21     /**
 22        Computes a Fibonacci number.
 23        @param n an integer
 24        @return the nth Fibonacci number
 25     */
 26     public static long fib(int n)
 27     {  
 28        if (n <= 2) { return 1; }
 29        long olderValue = 1;
 30        long oldValue = 1;
 31        long newValue = 1;
 32        for (int i = 3; i <= n; i++)
 33        {  
 34           newValue = oldValue + olderValue;
 35           olderValue = oldValue;
 36           oldValue = newValue;
 37        }
 38        return newValue;
 39     }
 40  }