In the 13th century, the Italian mathematician Leonardo Fibonacci, as a way to explain the geometric growth of a population of rabbits, devised a mathematical sequence that now bears his name. The first two terms in this sequence, Fib(0) and Fib(1), are 0 and 1, and every subsequent term is the sum of the preceding two. Thus, the first several terms in the Fibonacci sequence look like this:

Fib(0) = 0
Fib(1) = 1
Fib(2) = 1 (0 + 1)
Fib(3) = 2 (1 + 1)
Fib(4) = 3 (1 + 2)
Fib(5) = 5 (2 + 3)

Write a program that displays the terms in the Fibonacci sequence, starting with Fib(0) and continuing as long as the terms are less than 10,000. Thus, your program should produce the following sample run:

This program should continue as long as the value of the term is less than the maximum value. To do this, you should use a while loop, presumably with a header line that looks like this:

while (term < MAX_TERM_VALUE)
Note that the maximum term value is specified using a named constant.

Solution

/*
* File: Fibonacci.java
* --------------------
* This program lists the terms in the Fibonacci sequence up to
* a constant MAX_TERM_VALUE, which is the largest Fibonacci term
* the program will display.
*/

import acm.program.*;

public class Fibonacci extends ConsoleProgram {

/* Defines the largest term to be displayed */
private static final int MAX_TERM_VALUE = 10000;

public void run() {
println("This program lists the Fibonacci sequence.");
int t1 = 0;
int t2 = 1;
while (t1 <= MAX_TERM_VALUE) {
println(t1);
int t3 = t1 + t2;
t1 = t2;
t2 = t3;
}
}

}