Question:
Need a java program the prints out the Fibonacci sequence.
Answer:
This program prints out the first 20 numbers in the Fibonacci sequence. Each number is formed by adding together the previous two numbers in the sequence, starting with the numbers 0 and 1.
Code:
public class Fibonacci { public static void main(String[] args) { int current = 1; int prev = 0; int prevprev = 0; System.out.print("0 "); for(int i = 1; i < 20; i++) { prevprev = prev; prev = current; current = prev + prevprev; System.out.print(current + " "); } System.out.println(); } }
Output:
$ java Fibonacci 0 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765