The Fibonacci numbers are a sequence of integers in which the first two elements are 1, and each following element is the sum of the two preceding elements. The mathematical definition of each kth Fibonacci number is the following:
The first 12 Fibonacci numbers are
1 1 2 3 5 8 13 21 34 55 89 144
Write a for loop that computes and prints the first 12 Fibonacci numbers.
Program:
public class Ch02Ex03
{
public static final int MAX = 12;
public static void main(String[] args)
{
int f1;
int f2;
int fk;
f1 = 1;
f2 = 1;
System.out.print(f1 + " ");
System.out.print(f2 + " ");
for(int k = 3; k <= MAX; k++)
{
fk = f2 + f1;
System.out.print(fk + " ");
f1 = f2;
f2 = fk;
}
}
}
Output:
1 1 2 3 5 8 13 21 34 55 89 144