How do I print a diamond pattern using loops in Java?

You can build a diamond pattern by combining a growing pyramid with a shrinking pyramid. Print the widest row only once so the two halves meet at a single center row.

Source code

Save this example as DiamondPatternExample.java.

public class DiamondPatternExample {
    public static void main(String[] args) {
        int halfHeight = 5;

        for (int row = 1; row <= halfHeight; row++) {
            for (int space = 0; space < halfHeight - row; space++) {
                System.out.print(" ");
            }
            for (int star = 0; star < 2 * row - 1; star++) {
                System.out.print("*");
            }
            System.out.println();
        }

        for (int row = halfHeight - 1; row >= 1; row--) {
            for (int space = 0; space < halfHeight - row; space++) {
                System.out.print(" ");
            }
            for (int star = 0; star < 2 * row - 1; star++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

Explanation

The first outer loop prints the top half, including the widest row. Its row value increases from 1 to halfHeight. Each row prints halfHeight - row spaces followed by 2 * row - 1 stars.

The second outer loop prints the bottom half. It starts at halfHeight - 1 to avoid repeating the widest row, and decreases to 1. As row decreases, there are more leading spaces and fewer stars.

For a positive halfHeight, the diamond has 2 * halfHeight - 1 rows and the same number of stars in its widest row. A value of five therefore produces nine rows with nine stars across the center. Use a monospaced font to preserve alignment.

Run the example

With a JDK installed, open a terminal in the directory containing the source file and run:

javac DiamondPatternExample.java
java DiamondPatternExample

Output

    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *

Display the output in a monospaced font to keep the pattern aligned. Trailing spaces are omitted from the output shown here.

Try it yourself

Change halfHeight to 3. Then try 1 and observe why the bottom loop does not execute for that value.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.