Diamond.java


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


/******************************************************************************
 *  Compilation:  javac Diamond.java
 *  Execution:    java Diamond n
 *  
 *  Prints out a (2n+1)-by-(2n+1) diamond like the one below.
 *
 *  % java Diamond 4
 *  . . . . * . . . . 
 *  . . . * * * . . . 
 *  . . * * * * * . . 
 *  . * * * * * * * . 
 *  * * * * * * * * * 
 *  . * * * * * * * . 
 *  . . * * * * * . . 
 *  . . . * * * . . . 
 *  . . . . * . . . . 
 *
 ******************************************************************************/

public class Diamond {

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

        for (int i = -n; i <= n; i++) {
            for (int j = -n; j <= n; j++) {
                if (Math.abs(i) + Math.abs(j) <= n) System.out.print("* ");
                else                                System.out.print(". ");
            }
            System.out.println();
        }
    }
}


Copyright © 2000–2017, Robert Sedgewick and Kevin Wayne.
Last updated: Fri Oct 20 14:12:12 EDT 2017.