Learn how to print a square pattern in the C programming language.

How to print a square pattern with asterisks or a custom character in the C language

If you are an student, you may probably will have to solve the problematic of printing a square with some character, usually an asterisk, of X length in some predefined programming language. In this case, we'll explain you how to achieve with the C language.

The logic to print a square with a character on the console is the following. As first you need to define what's the length of the characters that will be printed, this assigns at the same time the number of rows. In our case, we'll prompt for it with the scanf function of C. Once you have the value, for example 5, you will need to iterate over this number with a for loop 5 times, on every iteration you will execute another loop that prints continously the given number the character that you want to use to draw the shape, in this case the asterisk. As well, once the second for loops ends, print a new line that is equivalent to another row:

#include<stdio.h>

int main()
{
    int i, j, Side;

    printf("Provide how long should a side should be e.g 4: \n");
    scanf("%d", &Side);

    for(i = 0; i < Side; i++)
    {
        for(j = 0; j < Side; j++)
        {
            printf("*");
        }

        // Add a new row
        printf("\n");
    }

    return 0;
}

This program will prompt the user for a number that defines the measure of the square and then it will print the shape with the designed length (see article's image).

Print square with a custom character

If instead of a single asterisk, you may change the character that the figure should use, for example an ampersand (&) or other characters (@,=,$,#). Follow the same logic, but create an extra variable of the char type that will be updated by the requested value:

/* C program to Print Square Pattern */
#include<stdio.h>

int main()
{
    int i, j, Side;
    char Ch;

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

    printf("Please Enter Any Side of a Square\n");
    scanf("%d", &Side);

    for(i = 0; i < Side; i++)
    {
        for(j = 0; j < Side; j++)
        {
           printf("%c", Ch);
        }
        
        printf("\n");
    }
    
    return 0;
}

This program will prompt for 2 values, the measure of the square and the character that will be used to draw it:

Print Square with custom measure and character in C

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