Print square pattern of Character in C

In this article, we are going to learn about how to print Character Patter in C Language using ASCII and maths numbers. Pattern programs are a good exercise to master the loops in the C language. Here in this example,

we will try to print below two types of patterns


  • Print a square matrix box of number where user enters the size.
  • Print a square matrix box of characters where user enters the size.

Print square pattern of Numbers in C


In this example, we will print the square matrix with the help of for loop and numbers. We will ask the user to enter the size and then we will print the square matrix using numbers.

Desired Output for Size 3:
1 1 1
2 2 2
3 3 3

First, we are asking the user to enter his desired size, once the user enters the size we save it in a variable. Then we iterate on two for loops to the max of this input value from the user. For each iteration of the row, we are iterating on full column length and printing the row number. On each row iteration, we switch to the next line using “\n”.

Program to print square pattern of number in C

#include<stdio.h>
int main()
{
   int num;

   printf("Please enter the size of Square Box: ");
   scanf("%d",&num);

   for(int row=1; row<=num; row++)
   {
     for(int col=1; col<=num; col++)
     {
       printf("%3d",row);
     }
     printf("\n");
   }

   return 0;
}

Output


Print square pattern of Character in C


In this example, we will print the square matrix with the help of for loop and characters. We will ask the user to enter the size and then we will print the square matrix using characters. This is similar to the above example, but here we are making use of the ASCII codes of the numbers to print them in character form.

Desired Output:
a a a
b b b
c c c

First, we are asking the user to enter his desired size, once the user enters the size we save it in a variable. Then we iterate on two for loops to the max of this input value from the user. For each iteration of the row, we are iterating on full column length and printing the row number+96. This 96 is taking us to the ASCII code of this row number and we are printing this number as a character by using a %3c character format specifier. On each row iteration, we switch to the next line using “\n”.

Program to Print square pattern of Character in C

#include<stdio.h>
int main()
{
   int num;
   printf("Please enter the size of Square Box: ");
   scanf("%d",&num);

   for(int row=1; row<=num; row++)
   {
     for(int col=1; col<=num; col++)
     {
       printf("%3c",row+96);
     }
     printf("\n");
   }

   return 0;
}

Output

Please enter the size of Square Box: 5
  a  a  a  a  a
  b  b  b  b  b
  c  c  c  c  c
  d  d  d  d  d
  e  e  e  e  e