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

To print a centered pyramid, print leading spaces before the stars on each row. As the row number increases, the number of spaces decreases and the number of stars increases.

Source code

Save this example as PyramidPatternExample.java.

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

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

Explanation

Each row contains two parts: leading spaces and stars. The first inner loop prints height - row spaces. The second inner loop prints 2 * row - 1 stars, giving the sequence 1, 3, 5, 7, and 9.

For a height of five, the first row has four spaces and one star. The last row has no leading spaces and nine stars. Adding two stars per row keeps the pyramid centered in a monospaced font.

This example prints "*" instead of "* ". Each star and each space occupies one character position, which makes the centering formula work as written. The two inner loops run one after the other for every row.

Run the example

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

javac PyramidPatternExample.java
java PyramidPatternExample

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

Set height to 3. Calculate the number of leading spaces and stars for each row before running the program.

Leave a Reply

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