Hollow Square Border Numbers in C++

Beginner
⏱️ 7 min read
📚 Updated: Aug 2025
🎯 2 Code Examples
Formatting (setw)

What You’ll Learn

How to print a hollow square border number pattern in C++ using nested loops and conditional logic.

You’ll also see how setw keeps numbers aligned in a grid so the pattern stays readable.

⭐ Pattern Output

For rows = 5, the pattern looks like this:

Output
  1  2  3  4  5
 16          6
 15          7
 14          8
 13 12 11 10  9
1

Complete C++ Program

We print numbers only on the border using if/else. The inside cells print spaces, and setw(3) aligns the columns.

C++
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    int i, j;
    int k = 6, l = 13, m = 16;

    for (i = 1; i <= 5; i++) {
        for (j = 1; j <= 5; j++) {
            if (i == 1)
                cout << setw(3) << j;
            else if (j == 5)
                cout << setw(3) << k++;
            else if (i == 5)
                cout << setw(3) << l--;
            else if (j == 1)
                cout << setw(3) << m--;
            else
                cout << "   ";
        }
        cout << "\n";
    }

    return 0;
}

🧠 How It Works

1

Loop over a grid

The nested loops go through every cell in a 5×5 grid: i is the row and j is the column.

Grid scan
2

Top row (1..5)

When i == 1, we print j, producing 1 2 3 4 5.

Top edge
3

Right edge, bottom edge, left edge

For the other borders, we print counters (k, l, m) using setw(3) so everything stays aligned.

Border fill
4

Inside cells stay blank

If the cell is not on the border, we print three spaces: " ".

Hollow
=

Hollow square border

We check each grid position once, so the time complexity is about O(n²) for an \(n \times n\) grid.

2

Variation — User Input Version

This version reads the size and computes the starting values from rows, so it scales beyond 5×5.

C++
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    int rows;
    cout << "Enter the number of rows (>= 2): ";
    cin >> rows;

    if (rows < 2) return 0;

    int i, j;
    int k = rows + 1;         // right edge starts after 1..rows
    int l = 3 * rows - 2;     // bottom-left for rows=5 -> 13
    int m = 4 * rows - 4;     // left edge top value for rows=5 -> 16

    for (i = 1; i <= rows; i++) {
        for (j = 1; j <= rows; j++) {
            if (i == 1)
                cout << setw(3) << j;
            else if (j == rows)
                cout << setw(3) << k++;
            else if (i == rows)
                cout << setw(3) << l--;
            else if (j == 1)
                cout << setw(3) << m--;
            else
                cout << "   ";
        }
        cout << "\n";
    }

    return 0;
}

💡 Tips for Enhancement

Try These

  • Increase setw width when rows is large (multi-digit numbers)
  • Fill the inside with a different symbol (e.g., .) to visualize the grid
  • Print the numbers in clockwise vs anti-clockwise order by adjusting the border logic
  • Create a fully filled square by printing numbers for all cells
  • Wrap the border-printing logic into a function for reuse

Avoid

  • Mixing different widths/spaces (it will break alignment)
  • Forgetting to print spaces for inner cells
  • Using endl inside loops (slower than "\n")
  • Accepting rows < 2 without handling it

Key Takeaways

1

Scan a grid with nested loops and print only when you’re on the border.

2

setw helps keep numbers aligned in columns.

3

Separate border segments (top/right/bottom/left) using clear conditions.

4

This conditional-print approach is useful for many hollow shapes.

❓ Frequently Asked Questions

Because we print three spaces for any cell that is not on the border. That keeps the square hollow.
Yes. Instead of checking only row 1 / row n / col 1 / col n, you can treat a band (e.g., first two rows/cols) as border.
They let each border segment continue the numbering in the right direction (down, then left, then up) without complex arithmetic.
O(n²) for an \(n \times n\) grid, since every cell is visited once.

Explore More C++ Number Patterns!

Keep practicing border, hollow, and symmetric patterns to strengthen your loop logic.

All Number Patterns →
Did you know?

Border patterns are a gentle introduction to matrix thinking: every output position is a cell \((i, j)\), and simple conditions decide what appears in that cell.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful