Facebook Pixel

Printing a Hollow Square Star Pattern

Dive into coordinate-based pattern printing by utilizing conditional statements to carve out the center of a square matrix.

Carving the Grid

Printing a solid square is easy (two nested loops). Printing a hollow square introduces a new concept: conditional printing based on matrix coordinates.

The Problem

Print a hollow square of size N. If N = 4:

****
*  *
*  *
****

The Coordinate Check

To solve this, we generate a full N x N grid using two loops, but we use an if statement to decide whether to print a star * or a blank space .

When does a star appear?

  • On the very first row (row == 1)
  • On the very last row (row == n)
  • On the very first column (col == 1)
  • On the very last column (col == n)

The Implementation

int n = 4;
for (int row = 1; row <= n; row++) {
    for (int col = 1; col <= n; col++) {
        // If it's a boundary coordinate, print a star
        if (row == 1 || row == n || col == 1 || col == n) {
            System.out.print("*");
        } else {
            // Otherwise, print empty space
            System.out.print(" ");
        }
    }
    System.out.println();
}

Why This Matters

This is the exact logic used in 2D array boundary traversal. If you need to write an algorithm that only processes the exterior walls of a maze or a matrix, you use this exact boolean logic.

The Takeaway

Hollow shapes cannot be solved by simply adjusting the loop boundaries. They require full grid traversal with internal conditional logic acting as a filter for the specific coordinates you care about.

Generate an N x N grid and print a star only if the current row or column is at the absolute boundary (1 or N). Otherwise, print a space.

You could, but it is incredibly messy. Coordinate-based boolean logic is the standard and most readable way to handle hollow shapes.

Because terminal fonts are usually taller than they are wide. A star (*) takes up more vertical space than horizontal space. You can fix this by printing '* ' (with a space) to widen the shape.

This exact boundary logic (checking if row==0 or col==max) is used in graph traversal algorithms (like BFS/DFS in a matrix) to detect when you hit a wall.

The logic is identical, just replace 'row == n' with 'row == height' and 'col == n' with 'col == width'.

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.