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

You can print a square pattern with two nested for loops. The outer loop controls the rows, and the inner loop prints the same number of stars in each row.

Source code

Save this example as SquarePatternExample.java.

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

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

Explanation

The variable size determines both the number of rows and the number of stars per row. With size = 5, the outer loop runs five times. For each row, the inner loop also runs five times, producing 25 stars in total.

System.out.print("* ") prints a star followed by a space without starting a new line. After the inner loop finishes, System.out.println() moves to the next row. Placing that line break inside the inner loop would print each star on a separate line.

The pattern has equal numbers of rows and columns. Its apparent proportions depend on the terminal font and spacing; text cells are not necessarily square.

Run the example

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

javac SquarePatternExample.java
java SquarePatternExample

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 size to 3, then to 7. Before running the program, predict how many stars it will print using size * size.

Leave a Reply

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