How to Print a Square Star Pattern
Master the most basic nested loop structure by writing the code to print a solid N x N square matrix of stars.
The Foundation of 2D Grids
The square pattern is the simplest pattern. It forms the baseline for understanding how two independent loops create a grid.
The Problem
Print an N x N square of stars. If N = 3:
***
***
***
The Analysis
- Rows: There are exactly N rows. So the outer loop runs from 1 to N.
- Columns: Every single row has exactly N stars.
- Relationship: Unlike a triangle, the number of columns does not depend on the current row. It is always N.
The Code Implementation (Java/C++)
int n = 3;
for (int row = 1; row <= n; row++) {
// Inner loop always runs exactly 'n' times
for (int col = 1; col <= n; col++) {
System.out.print("*"); // Print on the same line
}
System.out.println(); // Move to the next line
}
Understanding the Flow
row = 1: The inner loop runs 3 times, printing***. Then a newline is printed.row = 2: The inner loop runs 3 times, printing***. Then a newline is printed.row = 3: The inner loop runs 3 times, printing***. Then a newline is printed.
The Takeaway
The square pattern teaches you that when the inner loop's boundary is completely static (always N), you get a perfect grid. This is the exact code structure you will use to iterate over a 2D matrix in graph traversal problems.
In a square pattern, the number of columns printed is constant and does not depend on which row is currently being printed.
The outer loop runs N times, and the inner loop runs N times. Therefore, the time complexity is exactly O(N^2).
Instead of both loops running up to N, the outer loop runs up to the 'height' variable, and the inner loop runs up to the 'width' variable.
Using 'print' keeps the output on the same horizontal line. Using 'println' would output each star on a completely new line, ruining the grid.
Yes, traversing a 2D array matrix uses the exact same nested loop structure, substituting 'row' and 'col' for array indices.
