Loops.java


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


/******************************************************************************
 *  Compilation:  javac Loops.java
 *  Execution:    java Loops
 *
 *  Various loops.
 ******************************************************************************/

public class Loops {

    public static void main(String[] args) {

        int n = Integer.parseInt(args[0]);

        // print powers of two
        int power = 1;
        for (int i = 0; i <= n; i++) {
            System.out.println(power);
            power = 2 * power;
        }
        System.out.println();

        // print largest power of two less than or equal to n
        power = 1;
        while (power <= n/2) {
            power = 2 * power;
        }
        System.out.println("largest power of two <= " + n + " = " + power);
        System.out.println();

        // compute a finite sum (1 + 2 + ... + n)
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        System.out.println("sum of first " + n + " positive integers = " + sum);
        System.out.println();

        // compute a finite product (n!)
        int product = 1;
        for (int i = 1; i <= n; i++) {
            product *= i;
        }
        System.out.println(n + "! = " + product);
        System.out.println();

        // print a table of values (2 pi i / n)
        for (int i = 0; i <= n; i++) {
            System.out.println(i + " " + 2 * Math.PI * i / n);
        }
        System.out.println();

        // print the ruler function
        String ruler = " ";
        for (int i = 1; i <= n; i++) {
            ruler = ruler + i + ruler;
        }
        System.out.println(ruler);
        System.out.println();

    }
}


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