Facebook Pixel

Translating Visual Patterns into Coordinate Logic

Learn how to solve complex hollow patterns by treating the terminal as an X-Y coordinate plane and writing boolean conditions.

Programming as Geometry

Some patterns cannot be solved by simply counting stars and spaces. What if you need to print a hollow square? Or an 'X' shape?

To solve these, you must stop thinking about "how many stars to print" and start thinking about "what coordinates get a star."

The Coordinate Approach

Set up a standard N x N nested loop. This gives you a grid of coordinates from (1,1) to (N,N).

for (int row = 1; row <= n; row++) {
    for (int col = 1; col <= n; col++) {
        // Condition goes here
    }
}

Solving a Hollow Square

When does a hollow square have stars? Only on the absolute borders.

  • Top row: row == 1
  • Bottom row: row == n
  • Left column: col == 1
  • Right column: col == n

You simply combine these with an OR (||) operator:

if (row == 1 || row == n || col == 1 || col == n) {
    print("*");
} else {
    print(" ");
}

Solving an 'X' Pattern

When does an 'X' have stars? On the two diagonals.

  • The main diagonal is where X equals Y: row == col.
  • The anti-diagonal is where X + Y equals N + 1: row + col == n + 1.
if (row == col || row + col == n + 1) {
    print("*");
} else {
    print(" ");
}

The Takeaway

When a pattern has complex empty space inside of it, stop using multiple inner loops. Generate a full N x N grid and use geometric boolean logic to decide whether to print a star or a space at each specific (row, col) coordinate.

It is a technique where you generate a full N x N grid and use an if-else statement to determine if the current (row, column) coordinate should contain a star or a blank space.

Use an N x N loop. If the current row is the first or last, OR the current column is the first or last, print a star. Otherwise, print a space.

The main diagonal (top-left to bottom-right) occurs wherever the row index exactly equals the column index (row == col).

The anti-diagonal (top-right to bottom-left) occurs where the sum of the row and column indices equals N + 1 (assuming 1-based indexing).

Because trying to calculate leading, internal, and trailing spaces using multiple sequential inner loops for hollow shapes requires incredibly complex math, whereas coordinate logic is a simple boolean check.

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.