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

You can print a hollow pyramid by placing stars along its two sloping sides and its base. Nested for loops control the leading spaces and the width of each row, while an if statement leaves the interior empty.

Source code

Save this example as HollowPyramidPatternExample.java. It uses a compact source file with void main() and the IO console methods. Use JDK 25 or later; no preview flags or external libraries are required. Compact source files allow the method to appear without an explicit class declaration. See the Java documentation on compact source files.

void main() {
    int height = 5;

    for (int row = 1; row <= height; row++) {
        for (int space = 0; space < height - row; space++) {
            IO.print(" ");
        }
        for (int column = 1; column <= 2 * row - 1; column++) {
            if (column == 1 || column == 2 * row - 1 || row == height) {
                IO.print("*");
            } else {
                IO.print(" ");
            }
        }
        IO.println();
    }
}

Explanation

The outer loop counts from 1 through height, producing one line for each row. Two inner loops run in sequence on that line.

The first inner loop prints height - row leading spaces. With a height of five, the leading-space counts are 4, 3, 2, 1, and 0. Reducing this count moves the left edge one position to the left on each successive row.

The second inner loop visits 2 * row - 1 positions. Its width increases through the odd numbers 1, 3, 5, 7, and 9. This makes the right edge move one position to the right while the left edge moves left, keeping the pyramid centered.

At each position, the condition checks whether a star belongs there:

Condition Purpose
column == 1 Print the left edge.
column == 2 * row - 1 Print the right edge.
row == height Fill the entire bottom row.

The logical OR operator, ||, selects a star when any of these conditions is true. All remaining positions contain a single space, creating the empty interior. On the first row, the left and right edges share one position, so only one star is printed.

Both the star and the empty position occupy one character. Use "*" rather than "* " here so the spacing matches the leading-space calculation.

IO.print() writes without ending the current line. After both inner loops finish, IO.println() starts the next row. The IO class is available without an explicit import because it belongs to java.lang.

Run the example

With JDK 25 or later installed, open a terminal in the directory containing the source file and run it directly:

java HollowPyramidPatternExample.java

The Java launcher compiles and runs the source file. You can also compile it explicitly and then run the compiled program:

javac HollowPyramidPatternExample.java
java HollowPyramidPatternExample

Output

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

Display the output in a monospaced font to preserve alignment. Leading spaces are part of the pattern.

Try it yourself

Change height to 3, then to 7. For each row, calculate the number of leading spaces and the row width before running the program. A positive height n produces n rows and a base of 2 * n - 1 stars.

Try height = 1, which prints a single star, and height = 2, which prints a tip above a three-star base. Neither has an empty interior. A zero or negative height produces no output because the outer loop never executes.

Finally, remove || row == height from the condition to leave the base open. Compare the result with the filled shape in How do I print a pyramid pattern using loops in Java?.

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

You can print a checkerboard pattern by alternating stars and empty positions across a grid. Use nested for loops to visit each position and the remainder operator % to decide which positions contain stars.

Source code

Save this example as CheckerboardPatternExample.java.

public class CheckerboardPatternExample {
    public static void main(String[] args) {
        int size = 8;

        for (int row = 0; row < size; row++) {
            for (int column = 0; column < size; column++) {
                if ((row + column) % 2 == 0) {
                    System.out.print("* ");
                } else {
                    System.out.print("  ");
                }
            }
            System.out.println();
        }
    }
}

Explanation

The variable size sets both the number of rows and the number of logical columns. The outer loop selects each row, and the inner loop visits each column in that row. Both counters start at zero, so a size of eight gives indexes from 0 through 7.

The expression (row + column) % 2 calculates the remainder after dividing the sum of the indexes by two. A remainder of zero means the sum is even; a remainder of one means it is odd. The program prints a star for an even sum and an empty position for an odd sum.

For the first two rows, the condition works like this:

Row Column Sum Remainder Result
0 0 0 0 Star
0 1 1 1 Empty
0 2 2 0 Star
1 0 1 1 Empty
1 1 2 0 Star
1 2 3 1 Empty

Moving one position horizontally increases column by one, changing the sum from even to odd or from odd to even. Moving one position vertically increases row by one and also changes the parity. This makes neighboring positions alternate in both directions.

Using only column % 2 would repeat the same arrangement on every row and produce vertical stripes. Including row shifts the arrangement on alternate rows, creating the checkerboard pattern.

Each star position prints "* ", and each empty position prints " ". Both strings occupy two character positions, so the columns stay aligned. System.out.println() runs after the inner loop to start the next row.

Run the example

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

javac CheckerboardPatternExample.java
java CheckerboardPatternExample

Output

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

Display the output in a monospaced font to preserve alignment. Trailing spaces are omitted from the output shown here; leading spaces are preserved. Every row still contains eight logical positions, including empty positions at its edges. The stars mark alternating cells rather than drawing solid squares.

Try it yourself

Change size to 5. Odd sizes also work: the first and last positions of the first row both contain stars. With a size of five, the program prints 13 stars across 25 logical positions. With the original size of eight, it prints 32 stars across 64 logical positions.

Change the condition to (row + column) % 2 != 0 to swap the starred and empty positions. The top-left position will then be empty.

To make the empty cells visible while learning, replace System.out.print(" ") with System.out.print(". "). Both branches still print two characters, preserving alignment.

Finally, try size = 1, which prints a single star. A zero or negative size produces no output because the outer loop never executes.

How do I print a plus sign pattern using loops in Java?

You can print a plus sign by placing stars along the middle row and middle column of a square grid. Use nested for loops to visit each position and an if statement to select the positions that form the sign.

Source code

Save this example as PlusSignPatternExample.java. It uses basic Java syntax and requires no external libraries. Choose a positive odd size to give the pattern a single center position and equal-length arms.

public class PlusSignPatternExample {
    public static void main(String[] args) {
        int size = 7;
        int middle = size / 2;

        for (int row = 0; row < size; row++) {
            for (int column = 0; column < size; column++) {
                if (row == middle || column == middle) {
                    System.out.print("* ");
                } else {
                    System.out.print("  ");
                }
            }
            System.out.println();
        }
    }
}

Explanation

The variable size controls the number of rows and logical columns. Both counters start at zero and stop before size, so a size of seven gives indexes from 0 through 6.

The expression size / 2 calculates the middle index. Because both operands are integers, Java performs integer division. With size = 7, the result is 3. Index 3 has three positions before it and three after it.

The outer loop selects each row, while the inner loop visits every column in that row. The if statement checks two conditions:

Condition Part of the pattern
row == middle The horizontal line across the middle row
column == middle The vertical line down the middle column

The logical OR operator, ||, selects a position when either condition is true. On the middle row, every position contains a star. On every other row, only the middle column contains a star.

At the center, both conditions are true, but the if body executes only once. The center star therefore belongs to both lines without being printed twice.

Each star position prints "* ", and each empty position prints " ". Both strings occupy two character positions, keeping the vertical line aligned. After the inner loop finishes, System.out.println() starts the next row.

Run the example

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

javac PlusSignPatternExample.java
java PlusSignPatternExample

Output

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

Display the output in a monospaced font to preserve alignment. Trailing spaces are omitted from the output shown here; leading spaces are preserved. The apparent proportions depend on the font and character spacing.

Try it yourself

Change size to 5, then to 9. Calculate middle before running each version. For a positive odd size n, the pattern contains 2 * n - 1 stars: n in the horizontal line and n in the vertical line, with the shared center counted once. The example with a size of seven prints 13 stars.

Try size = 6. The program still prints intersecting lines, but the arms are unequal because an even-sized grid has no single middle row or column. Integer division selects index 3, leaving three positions before the intersection and two after it. Use a positive odd size for the symmetric pattern shown above.

With size = 1, the output is a single star. A zero or negative size produces no output because the outer loop never executes.

Finally, replace || with && in the condition. Predict the output: logical AND requires both conditions to be true, so only the center position contains a star. Compare this row-and-column condition with the diagonal conditions in How do I print an X pattern using loops in Java?.

How do I print an X pattern using loops in Java?

You can print an X pattern by placing stars along the two diagonals of a square grid. Use nested for loops to visit each position and an if statement to check whether it belongs to either diagonal.

Source code

Save this example as XPatternExample.java.

public class XPatternExample {
    public static void main(String[] args) {
        int size = 7;

        for (int row = 0; row < size; row++) {
            for (int column = 0; column < size; column++) {
                if (row == column || row + column == size - 1) {
                    System.out.print("* ");
                } else {
                    System.out.print("  ");
                }
            }
            System.out.println();
        }
    }
}

Explanation

The variable size sets the number of rows and logical columns. Both loop counters start at zero and stop before size. For a size of seven, each counter visits the values 0 through 6.

The outer loop selects the current row, and the inner loop selects each column in that row. The condition checks the two diagonals:

Condition Diagonal Example positions for size 7
row == column Top-left to bottom-right (0, 0), (1, 1), (2, 2)
row + column == size - 1 Top-right to bottom-left (0, 6), (1, 5), (2, 4)

On the first diagonal, the row and column indexes are equal. On the second diagonal, their sum is always size - 1.

The logical OR operator, ||, makes the condition true when a position belongs to either diagonal. The program prints "* " for these positions and " " everywhere else. Both strings occupy two character positions, preserving the grid’s column alignment.

For an odd size, the diagonals share one center position. In this example, that position is (3, 3). Although both conditions are true there, the if body executes only once, so the program prints a single center star.

System.out.println() runs after the inner loop finishes, moving the output to the next row.

Run the example

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

javac XPatternExample.java
java XPatternExample

Output

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

Display the output in a monospaced font to preserve alignment. Trailing spaces are omitted from the output shown here; leading spaces are preserved. The apparent angle of each diagonal depends on the font and character spacing.

Try it yourself

Change size to 5, then to 6. An odd size produces one center star. An even size produces two adjacent stars on each of the two middle rows because the diagonals do not share a grid position.

For a positive odd size n, the pattern contains 2 * n - 1 stars. For a positive even size, it contains 2 * n stars. The example with a size of seven prints 13 stars.

Try size = 1, which prints a single star. A zero or negative size produces no output because the outer loop never executes.

Finally, remove one of the two diagonal conditions to print only a single diagonal. Compare these conditions with the border conditions in How do I print a hollow square pattern using loops in Java?.

How do I print a right-aligned triangle pattern using loops in Java?

You can print a right-aligned triangle by placing spaces before the stars on each row. As the number of stars increases, reduce the number of empty positions so the right edge stays aligned.

Source code

Save this example as RightAlignedTrianglePatternExample.java.

public class RightAlignedTrianglePatternExample {
    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 < row; star++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

Explanation

The outer loop counts from 1 through height. Its counter, row, determines how many stars to print on the current line.

Inside the outer loop, two loops run in sequence. The first prints height - row empty positions. The second prints row stars. These counts always add up to height, so every row occupies the same number of logical positions.

For a height of five, the counts are:

Row Empty positions Stars
1 4 1
2 3 2
3 2 3
4 1 4
5 0 5

Each empty position uses two spaces, " ". Each star position uses a star followed by a space, "* ". Both occupy two character positions, keeping the rightmost star in the same column on every row. Printing only one space per empty position would break this alignment.

On the first row, the program prints eight leading spaces followed by one star and its trailing space. On the last row, the leading-space loop does not execute because height - row is zero, and the star loop prints five stars.

System.out.print() writes each part on the current line. System.out.println() runs after both inner loops to start the next row.

Run the example

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

javac RightAlignedTrianglePatternExample.java
java RightAlignedTrianglePatternExample

Output

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

Display the output in a monospaced font to preserve alignment. Trailing spaces are omitted from the output shown here; leading spaces are preserved.

Try it yourself

Change height to 3, then to 7. For each row, calculate the number of empty positions and stars before running the program. A positive height n produces n rows and n * (n + 1) / 2 stars.

Try height = 1, which prints a single star without leading spaces. A zero or negative height produces no output because the outer loop never executes.

Finally, remove the first inner loop and compare the result with How do I print a right triangle pattern using loops in Java?. The number of stars stays the same, but the triangle becomes left-aligned.