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.

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