Hollow Square Border of 1s in C++

What You’ll Learn
How to print a hollow square where only the border is filled with 1 and the inside is blank.
This is a great pattern to practice:
- Row/column thinking (2D loops)
- Border detection using a simple condition
⭐ Pattern Output
For n = 5, the pattern looks like this:
1 1 1 1 1
1 1
1 1
1 1
1 1 1 1 1Complete C++ Program
Print 1 on the first/last row or first/last column; otherwise print spaces.
#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
Loop through rows
The outer loop chooses the row index i from 1 to 5.
Loop through columns
The inner loop chooses the column index j from 1 to 5.
Detect border cells
If i is 1 or 5, you’re on the top/bottom border. If j is 1 or 5, you’re on the left/right border.
Print 1 or blank
Border cells print "1 ", interior cells print spaces " ".
Hollow 1-square
You visit every cell once, so runtime is O(n²) for an n×n square.
Variation — User Input Version
Let the user choose the size n at runtime.
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter the value of n: ";
cin >> n;
if (n <= 0) return 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (i == 1 || i == n || j == 1 || j == n)
cout << "1 ";
else
cout << " ";
}
cout << "\n";
}
return 0;
}💡 Tips for Enhancement
Try These
- Replace
1with any character (e.g.,*or#) - Print a hollow square of
0s by changing the border print - Use two digits (like
10) and adjust spacing accordingly - Add input validation and re-prompt on invalid
n - Create a hollow rectangle by using separate
rowsandcols
Avoid
- Forgetting the newline after each row
- Using inconsistent spacing (your border won’t align)
- Allowing
nto be 0 or negative without handling it - Hard-coding sizes when you already have a variable
Key Takeaways
The border is detected with i==1 || i==n || j==1 || j==n.
Interior cells print spaces, creating a hollow look.
This technique generalizes to hollow rectangles and other borders.
Runtime is O(n²) for an n×n grid.
❓ Frequently Asked Questions
i==1 || i==n || j==1 || j==n checks."1 " (a 1 plus a trailing space) so the columns line up nicely.if and always print "1 " inside the inner loop.Explore More C++ Number Patterns!
Border checks like this show up everywhere—from hollow shapes to matrix problems.
Hollow patterns are a common introduction to 2D grid logic. The same border idea is used in image processing and matrix traversal problems.
12 people found this page helpful
