Hollow Square Number Border Pattern in C

What You’ll Learn
How to print a hollow square where only the border contains numbers, and the inside is empty (spaces). This is a good exercise for combining nested loops with border conditions.
⭐ Pattern Output
For size = 5, the pattern looks like this:
Output
1 2 3 4 5
16 6
15 7
14 8
13 12 11 10 91
Complete C Program (Fixed Size)
This version prints a 5×5 hollow square border. The width %-3d keeps spacing consistent.
c
#include <stdio.h>
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)
printf("%-3d", j);
else if (j == 5)
printf("%-3d", k++);
else if (i == 5)
printf("%-3d", l--);
else if (j == 1)
printf("%-3d", m--);
else
printf(" ");
}
printf("\n");
}
return 0;
}2
Variation — User Input Size
This version reads the square size and computes border start values to keep the same numbering style.
c
#include <stdio.h>
int main() {
int i, j;
int size;
int k, l, m;
printf("Enter the size of the square: ");
scanf("%d", &size);
k = size + 1;
l = size * 3 - 2;
m = size * 3 + 1;
for (i = 1; i <= size; i++) {
for (j = 1; j <= size; j++) {
if (i == 1)
printf("%-3d", j);
else if (j == size)
printf("%-3d", k++);
else if (i == size)
printf("%-3d", l--);
else if (j == 1)
printf("%-3d", m--);
else
printf(" ");
}
printf("\n");
}
return 0;
}💡 Tips for Enhancement
Try These
- Change
%-3dto%-4dfor bigger numbers - Fill the interior with sequential numbers instead of spaces
- Use characters instead of numbers to print an alphabet border
Avoid
- Using a very small size (like 1 or 2) without handling special cases
- Forgetting to print spaces for the interior (it won’t look hollow)
Key Takeaways
1
Border cells are detected using conditions on i and j.
2
The interior prints spaces to keep the square hollow.
3
Formatted printing (%-3d) keeps columns aligned.
4
Time complexity is O(n²) for an n×n square.
12 people found this page helpful
