Hollow Square Number Pattern in C

Beginner
⏱️ 5 min read
📚 Updated: Aug 2025
🎯 2 Code Examples
Border Condition

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 1
1

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.

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.

6 people found this page helpful