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?.

Leave a Reply

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