Hollow Square Number Pattern in C

What You’ll Learn
How to print a hollow square using 1s on the border and spaces inside. The key idea is to detect border cells with a simple condition.
⭐ Pattern Output
For size = 5, the pattern looks like this:
Output
1 1 1 1 1
1 1
1 1
1 1
1 1 1 1 11
Complete C Program
Print 1 when you are on the border; otherwise print spaces.
c
#include <stdio.h>
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) {
printf("1 ");
} else {
printf(" ");
}
}
printf("\n");
}
return 0;
}2
Variation — User Input Version
Let the user choose the square size at runtime:
c
#include <stdio.h>
int main() {
int size;
int i, j;
printf("Enter the size of the square: ");
scanf("%d", &size);
for (i = 1; i <= size; ++i) {
for (j = 1; j <= size; ++j) {
if (i == 1 || i == size || j == 1 || j == size) {
printf("1 ");
} else {
printf(" ");
}
}
printf("\n");
}
return 0;
}🧠 How It Works
1
Loop through every cell
Two loops iterate over rows (i) and columns (j).
Traversal
2
Detect the border
If you are on the first/last row or first/last column, print 1.
Condition
3
Print interior spaces
For interior cells, print spaces to keep the middle hollow.
Hollow
Key Takeaways
1
Border check: i == 1 || i == size || j == 1 || j == size.
2
Interior cells print spaces to create the hollow effect.
3
Time complexity is O(n²) for an n×n square.
4
You can swap 1 with any character/symbol for new variants.
6 people found this page helpful
