C++ Hollow Square Pattern (Border of 1s)

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

What Is This Pattern?

A hollow square border prints a character only on the edges of an n × n grid — first/last row and first/last column — and leaves the interior blank with spaces.

Remember
Rule: print "1 " on border cells; "  " inside

1 1 1 1 1
1       1
1       1
1       1
1 1 1 1 1     ← size = 5

Unlike Program 41 (centered pyramid of perfect squares), this shape is a flat grid with a per-cell border check.

How to Solve It

Visit every cell with nested loops; print the border character or two spaces based on row/column edges.

MethodIdeaBest for
Border conditionIf first/last row or column → "1 ", else " "Learning, interviews, exams
Custom characterSame condition; swap "1 " for "* " or "# "Quick variants once the shape clicks

Pseudocode

Pseudocode
for i from 1 to size:
    for j from 1 to size:
        if i is 1 or size, or j is 1 or size:
            print "1 " (no newline)
        else:
            print "  " (no newline)
    print newline

Cheat sheet

GoalPattern
Walk rowsfor (i = 1; i <= size; i++)
Walk columnsfor (j = 1; j <= size; j++)
Border testi == 1 || i == size || j == 1 || j == size
Print border / interiorcout << "1 " / cout << " "
End the rowcout << "\n";
Meaningful hollowUse size >= 2 (size 1 has no interior)

Printing Numbers vs Starting a New Line

APIEffectUse for
cout << "1 " / cout << " "Stays on the same lineEach cell
cout << "\n"Ends the current lineAfter the inner loop

Print cells without a newline, then end the row once. cout << endl also ends the line and flushes; "\n" is enough for these demos.

Live Preview

Change the square size and the hollow border updates instantly — including cell and border counts.

Whole numbers from 2 to 12. Tap a chip or type a value — the preview redraws as you go.

Live result 5×5 · 25 cells · 16 border
1 1 1 1 1
1       1
1       1
1       1
1 1 1 1 1

Worked Walkthrough — row i = 3, size = 5

Trace each column on the middle row — which cells are border vs interior.

jOn border?WhyPrints
1Yesj == 11
2Nointerior
3Nointerior
4Nointerior
5Yesj == size1

Row 3 output: 1 1. Full grid visits 5² = 25 cells; border cells = 4×5 - 4 = 16.

C++ Programs

Three complete programs: fixed 5×5, cin size, and an asterisk border. Use View Output to reveal sample results.

Example 1 — Fixed size = 5

Hard-coded grid size — ideal for first demos and screenshots.

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

int main()
{
    int i, j;

    for (i = 1; i <= 5; i++)
    {
        for (j = 1; j <= 5; j++)
        {
            if (i == 1 || i == 5 || j == 1 || j == 5)
                cout << "1 ";
            else
                cout << "  ";
        }
        cout << "\n";
    }

    return 0;
}

How It Works

1. Nested loops visit every cell. Outer i is the row; inner j is the column.

2. Border condition. If i or j is on an edge, print "1 "; otherwise print " " so columns stay aligned.

3. End the row. cout << "\n" only after the inner loop finishes.

When i = 1 or i = 5, every cell is on the border — a full line of ones.

Example 2 — User Input Size

Read size at runtime and use it in both loops and the border check. Prefer validating cin.

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

int main()
{
    int size;
    int i, j;

    cout << "Enter square size: ";
    cin >> size;

    for (i = 1; i <= size; i++)
    {
        for (j = 1; j <= size; j++)
        {
            if (i == 1 || i == size || j == 1 || j == size)
                cout << "1 ";
            else
                cout << "  ";
        }
        cout << "\n";
    }

    return 0;
}

How It Works

1. Prompt and read. Ask for a size, then store it in size.

2. Same border core. Only the source of size changes — never hard-code 5 in the condition.

3. Safer input tip. Prefer:

Safer input
if (!(cin >> size) || size < 2)
{
    cout << "Enter an integer greater than 1.\n";
    return 1;
}

Example 3 — Asterisk Border

Keep size = 5 but print * on the border instead of 1.

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

int main()
{
    int size = 5;
    int i, j;

    for (i = 1; i <= size; i++)
    {
        for (j = 1; j <= size; j++)
        {
            if (i == 1 || i == size || j == 1 || j == size)
                cout << "* ";
            else
                cout << "  ";
        }
        cout << "\n";
    }

    return 0;
}

How It Works

1. Same condition. The border test and interior spaces match Example 1 exactly.

2. Only the glyph changes. Swap "1 " for "* " (or "# ") in the if branch.

3. Keep two-character cells. Border and interior both print two characters so columns stay lined up.

Edge Cases & Pitfalls

Check these before calling the solution done.

no if

Solid square

Printing "1 " in every cell fills the grid. You need the border condition for a hollow center.

hard-code 5

Broken NxN

If loops use size but the condition still checks 5, larger grids mis-draw. Use size everywhere.

one space

Misaligned columns

Border uses two characters ("1 "). Interior must use " ", not a single space.

\n early

Column of cells

If cout << "\n" is inside the inner loop, each cell lands on its own line. End the row only after the inner loop.

size = 1

No hollow

Output is just 1 — no interior. Validate size >= 2 for interactive programs.

Bad cin

Validate size

Check cin >> size and require size >= 2 before the loops.

Time and Space Complexity

ProgramTimeExtra space
Border condition (Examples 1–3)O(size²)O(1)

An n × n grid visits n² cells once each. Border cells alone are 4n - 4 for n >= 2, but the loops still scan the whole grid. Only a few integers of extra memory.

Key Takeaways

  • Rule: print "1 " when i or j is on an edge; otherwise " ".
  • Align cells: border and interior both print two characters so columns line up.
  • Break the row: call cout << "\n" only after the inner loop.
  • Complexity: O(n²) time for an n × n grid; O(1) extra space.

One line: for each cell (i, j), print "1 " on the border else " ", then end the line after each row.

Frequently Asked Questions

A hollow square prints characters only on the border (first/last row and first/last column) and leaves the inside blank with spaces.
It checks if i is 1 or size, or if j is 1 or size. If any condition is true, it prints 1; otherwise it prints spaces.
Use a size variable and loop from 1 to size for both i and j. Update the border check to use size instead of 5 — see Example 2.
Each border cell uses "1 " (digit plus space). Interior cells use " " so columns stay aligned in the console.
Size 2 gives a thin border frame. Size 1 prints a single 1 with no hollow interior.
Printing a cell stays on the same line. Printing a newline ends the current line. Cells use cout without a newline; the row break uses cout << "\n" after the inner loop.
O(n²) for an n×n grid because each cell is visited once.
After cin >> size, check failure and require size ≥ 2 for a meaningful hollow frame.

Did you know?

Print 1 when i == 1, i == size, j == 1, or j == size; otherwise print spaces. A size × size grid visits n² cells — total prints = n².

Next: Right-Aligned Number Triangle

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

Program 43 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