C++ Hollow Square Number Pattern (Border)

Beginner
6 min read
Updated: Sep 2026
3 programs
Live preview

What Is This Pattern?

A hollow square border number pattern visits every cell of an n×n grid, but prints consecutive numbers only on the boundary — clockwise from the top-left — and leaves the inside blank.

Remember
Rule: top → right → bottom ← left ↑ (inner = three spaces)

  1  2  3  4  5
 16           6
 15           7
 14           8
 13 12 11 10  9     ← n = 5 (16 border cells)

Unlike Program 58 (diagonal diamond), this shape is a rectangle outline with side-specific counters and setw(3) alignment.

How to Solve It

Nested loops over rows and columns. Branch on side order (top, right, bottom, left). Use three counters for the non-top sides.

MethodIdeaBest for
Side countersif / else if per side + k, l, mLearning, interviews, demos
Compact traceSame logic with n = 3Quick dry-runs on paper

Pseudocode

Pseudocode
k = n + 1
l = 3 * n - 2
m = 4 * (n - 1)

for i from 1 to n:
    for j from 1 to n:
        if i == 1: print j (width 3)
        else if j == n: print k; k = k + 1
        else if i == n: print l; l = l - 1
        else if j == 1: print m; m = m - 1
        else: print three spaces
    print newline

Cheat sheet

GoalPattern
Grid loopsfor (i = 1; i <= n; i++) for (j = 1; j <= n; j++)
Top rowif (i == 1) cout << setw(3) << j;
Right columnelse if (j == n) cout << setw(3) << k++;
Bottom rowelse if (i == n) cout << setw(3) << l--;
Left columnelse if (j == 1) cout << setw(3) << m--;
Inner cellelse cout << " ";
Counter startsk = n+1, l = 3*n-2, m = 4*(n-1)

Printing Numbers vs Starting a New Line

APIEffectUse for
cout << setw(3) << value / " "Stays on the same lineEach cell
cout << "\n"Ends the lineAfter the column loop

Print each cell without a newline, then end the row once.

Live Preview

Change the square size and the clockwise hollow border updates instantly.

Use size from 2 to 9. Border cells = 4×(n−1). Tap a chip or type a value — the preview redraws as you go.

Live result 5×5 · 16 border
  1  2  3  4  5
 16           6
 15           7
 14           8
 13 12 11 10  9

Worked Walkthrough

Trace the four sides for n = 5 — notice why j == n is checked before i == n.

SideConditionValues
Topi == 11 2 3 4 5
Rightj == 5 (rows 2..5)6 7 8 9
Bottomi == 5 (cols 1..4)13 12 11 10
Leftj == 1 (rows 2..4)16 15 14

Bottom-right is claimed by the right branch (j == n), so the bottom loop never reprints corner 9.

C++ Programs

Three complete programs: fixed 5×5, cin size with formulas, and a compact 3×3 demo. Use View Output to reveal sample results.

Example 1 — Fixed 5×5 Border

Hard-coded grid with classic counter starts k = 6, l = 13, m = 16.

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. Top row. When i == 1, print column index j with width 3.

2. Right, bottom, left. k++ fills the right side, l-- the bottom, m-- the left.

3. Hollow inside. Any non-border cell prints three spaces so columns stay lined up.

Example 2 — User Input Size

Read n and compute counter starts with the same formulas used in the live preview.

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

int main()
{
    int n, i, j;
    int k, l, m;

    cout << "Enter square size (n): ";
    cin >> n;

    k = n + 1;
    l = 3 * n - 2;
    m = 4 * (n - 1);

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

    return 0;
}

How It Works

1. Same side logic. Only n and the three start formulas change.

2. Entering 4. Border cells = 4×3 = 12 — numbers run from 1 to 12.

3. Validate in real apps. Prefer checking cin failure and requiring n >= 2 (tip below).

Safer input tip
if (!(cin >> n) || n < 2)
{
    cout << "Please enter an integer >= 2.\n";
    return 1;
}

Example 3 — Compact 3×3 Border

Eight border cells and one hollow center — ideal for a paper dry-run.

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

int main()
{
    int n = 3;
    int i, j;
    int k = n + 1, l = 3 * n - 2, m = 4 * (n - 1);

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

    return 0;
}

How It Works

1. Tiny grid. Easy to dry-run every if / else if branch on paper.

2. Same formulas. k = 4, l = 7, m = 8 — proving the counters scale.

3. One hollow cell. Center (2,2) prints three spaces; everything else is border.

Edge Cases & Pitfalls

Check these before calling the solution done.

Branch order

Test j == n before i == n

Bottom-right must come from the right counter — otherwise the clockwise sequence breaks.

Alignment

Match inner width to setw(3)

Inner cells need exactly three spaces. Two spaces skew the grid once numbers hit two digits.

Headers

Include <iomanip>

Without it, setw will not compile.

Bad cin

Require n >= 2

Size 1 is a single cell; size 0 or negative skips the loops. Validate before printing.

Time and Space Complexity

ProgramTimeExtra space
Hollow border (Examples 1–3)O(n²)O(1)

Every cell of the n×n grid is visited once — quadratic in n. Border length is only 4(n - 1), but the nested loops still walk the full square. Extra memory is a handful of counters.

Key Takeaways

  • Rule: top j, right k++, bottom l--, left m--, else spaces.
  • Align: setw(3) for numbers, three spaces for hollow cells.
  • Break the row: call cout << "\n" only after the column loop finishes.
  • Complexity: O(n²) time, O(1) extra space.

One line: walk the square cell by cell, number the border clockwise, leave the inside blank.

Frequently Asked Questions

Check sides in order: top (i == 1), right (j == n), bottom (i == n), left (j == 1). Everything else is an inner cell.
Fixed width 3 keeps columns aligned when border numbers have one or two digits. Include <iomanip>.
For n=5: a hollow 5×5 grid with numbers 1–16 clockwise on the boundary; the inside stays blank.
Program 58 prints a diagonal mirror diamond. Program 59 prints a rectangular hollow border with separate counters per side.
k tracks the right column, l the bottom row (descending), m the left column (descending). Top uses j directly.
Printing a padded number or three spaces stays on the same line. Printing a newline ends the current row.
O(n²) for an n×n grid because every cell is visited once.
A 2×2 grid has no inner cells — every position is on the border (4 cells = 4×(2-1)).

Did you know?

This pattern is a hollow n×n border: top 1..n, right continuing up, bottom descending, left descending — inner cells are three spaces so columns stay aligned with setw(3).

Next: Remove Last Digit Pattern

Continue with the next pattern in the C++ number-pattern series.

Program 60 tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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