The Fibonacci sequence starts with the terms 1 and 1, and each successive 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 program:
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 */
}
}
}
No comments:
Post a Comment