Fibonacci.java


Below is the syntax highlighted version of Fibonacci.java from §1.3 Conditionals and Loops.


/******************************************************************************
 *  Compilation:  javac Fibonacci.java
 *  Execution:    java Fibonacci n
 *
 *  Prints out the first n Fibonacci numbers.
 *
 *  % java Fibonacci 8
 *  1
 *  1
 *  2
 *  3
 *  5
 *  8
 *  13
 *  21
 *  34
 *  55
 *
 ******************************************************************************/

public class Fibonacci {

    public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);
        int f = 0, g = 1;

        for (int i = 1; i <= n; i++) {
            f = f + g;
            g = f - g;
            System.out.println(f);
        }
    }
}


Copyright © 2000–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 10:12:31 EDT 2022.