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.

How do I print an inverted triangle pattern using loops in Java?

You can print an inverted triangle by reducing the number of stars on each successive row. Use a descending outer for loop to control the row length and an inner loop to print the stars.

Source code

Save this example as InvertedTrianglePatternExample.java.

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

        for (int row = height; row >= 1; row--) {
            for (int column = 1; column <= row; column++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

Explanation

The variable height sets the number of rows and the number of stars on the first row. With height = 5, the outer loop visits the values 5, 4, 3, 2, and 1.

The outer loop has three parts:

Part Purpose
int row = height Start with the longest row.
row >= 1 Continue while at least one star remains.
row-- Subtract one after completing each row.

The inner loop starts at column = 1 and continues while column <= row. It therefore prints exactly row stars. When the outer loop decreases row, the next execution of the inner loop prints one fewer star.

For example, when row is 5, the inner loop runs five times. When row becomes 4, the inner loop starts again at 1 and runs four times. This continues until the last row contains one star.

System.out.print("* ") prints a star followed by a space without moving to another line. After the inner loop finishes, System.out.println() ends the current row. No leading spaces are printed, so the triangle remains aligned to the left.

The descending loop uses row-- because its condition requires the counter to move toward 1. Changing it to row++ would move the counter in the wrong direction and prevent the intended five-row output.

Run the example

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

javac InvertedTrianglePatternExample.java
java InvertedTrianglePatternExample

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 height to 3, then to 7. Before running each version, predict the number of rows and the total number of stars. For a positive height n, the total is n * (n + 1) / 2. The example with a height of five prints 15 stars.

Also try height = 1, which prints a single star. A zero or negative height produces no output because the outer loop condition is false at the start.

To turn the pattern upright, replace the outer loop with for (int row = 1; row <= height; row++) and leave the inner loop unchanged. Compare the result with How do I print a right triangle pattern using loops in Java?.

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

You can print a hollow square by combining nested for loops with an if statement. The loops visit every position in a square grid, while the condition prints stars only along its border. Positions inside the square contain spaces.

Source code

Save this example as HollowSquarePatternExample.java.

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

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

Explanation

The variable size controls both the number of rows and the number of logical columns. The outer loop visits each row, and the inner loop visits each column in that row. Both counters start at 0 and stop before size, so the last index is size - 1.

A position belongs to the border when at least one of these conditions is true:

Condition Border
row == 0 Top
row == size - 1 Bottom
column == 0 Left
column == size - 1 Right

The || operator means logical OR. If any border condition is true, the program prints "* ". Otherwise, it prints " " to leave the interior empty.

Both strings occupy two character positions. Using only one space for an empty position would shift the right border to the left on the middle rows.

For size = 5, the first and last rows contain five stars each. The three middle rows contain a star at each end and three empty positions between them. The output contains 16 stars in total.

System.out.print() stays on the current line. After the inner loop finishes, System.out.println() starts the next row. Keep this line break inside the outer loop and outside the inner loop.

Run the example

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

javac HollowSquarePatternExample.java
java HollowSquarePatternExample

Output

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

Display the output in a monospaced font to keep the pattern aligned. Trailing spaces are omitted from the output shown here. The pattern has equal numbers of logical rows and columns; its apparent proportions depend on the font and character spacing.

Try it yourself

Change size to 3, then to 7. For a size of at least two, the number of border stars is 4 * (size - 1): the top and bottom rows contribute 2 * size stars, and the remaining rows contribute 2 * (size - 2) stars.

Also try size = 1 and size = 2. The first prints a single star; the second prints four stars. Neither has an empty interior. A zero or negative size produces no output because the outer loop never executes.

To review how nested loops print every position, see How do I print a square pattern using loops in Java?.