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 else
30 {
31 long olderValue = 1;
32 long oldValue = 1;
33 long newValue = 1;
34 for (int i = 3; i <= n; i++)
35 {
36 newValue = oldValue + olderValue;
37 olderValue = oldValue;
38 oldValue = newValue;
39 }
40 return newValue;
41 }
42 }
43 }