Java Reference
In-Depth Information
1.2. Variables
The next example prints a part of the Fibonacci sequence, an infinite se-
quence whose first few terms are
1
1
2
3
5
8
13
21
34
The Fibonacci sequence starts with the terms 1 and 1, and each suc-
cessive term is the sum of the previous two terms. A Fibonacci printing
program is simple, and it demonstrates how to declare variables, write
a simple loop, and perform basic arithmetic. Here is the Fibonacci pro-
gram:
class Fibonacci {
/** Print out the Fibonacci sequence for values < 50 */
public static void main(String[] args) {
int lo = 1;
int hi = 1;
System.out.println(lo);
while (hi < 50) {
System.out.println(hi);
hi = lo + hi; // new hi
lo = hi - lo; /* new lo is (sum - old lo)
that is, the old hi */
}
 
Search WWH ::




Custom Search