Learn how to print only the border of a square (hollow box) with asterisks or a custom character in the C programming language.

How to print a hollow square/box/rectangle pattern with asterisks or a custom character in the C language

When I needed to do this on the university in the introduction to programming, achieving this task gave me a couple of extra points for the final note of the work of Loops.  In this article, we'll share with you a very simple script to create a hollow box/square output according to X number of asterisks on every side in the console with the C programming language:

#include<stdio.h>

void main()
{
    int number;
    
    printf("Provide the number of asterisks by side: \n");

    scanf("%d", &number);

    for (int i = 1; i <= number; i++) {
        for (int j = 1; j <= number; j++) {
            if (i == 1 || i == number || j == 1 || j == number){
                printf("* ");
            }else{
                printf("  ");
            }
        }

        printf("\n");
    }
}

The program will prompt for the number of asterisks that will be used for every side of the square and will print the output shown in the example at the beginning of the article.

Print pattern with custom character

In the following snippet, the user will be able to insert the custom character that will be used to draw the square:

#include<stdio.h>

void main()
{
    int number;
    char Ch;

    printf("Please Enter any Symbol\n");
    scanf("%c", &Ch);

    printf("Provide the number of asterisks by side: \n");

    scanf("%d", &number);

    for (int i = 1; i <= number; i++) {
        for (int j = 1; j <= number; j++) {
            if (i == 1 || i == number || j == 1 || j == number){
                printf("%c", Ch);
            }else{
                printf(" ");
            }
        }

        printf("\n");
    }
}

As with a custom pattern you may be not able to control the horizontal measure of every character, you may want to print only the character without extra spaces, otherwise the shape won't be exact.

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors