In this article, we are going to learn about how to print Print square Pattern in C language of “*” and numbers. Pattern programs are a good exercise to master the loops in the C language. Here in this example
we will try to print two types of patterns.
- Using * , print a square matrix box where user enters the size.
- Using Numbers , print a square matrix box where user enters the size.
1. Print start square pattern in C
In this example, we will print the square matrix with the help of for loop and “*” asterisk character. User will enter the size of this square matrix box and we will print the box with the help of “*”.
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, we are printing the “*” n times for the nth iteration. On each row iteration, we switch to the next line using “\n”.
Desired Output for size 3:-
* * *
* * *
* * *
#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("* ");
}
printf("\n");
}
return 0;
}
Output
Please enter the size of Square Box: 5
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
2. Print number square pattern
This is another variant of the program above, to print a square matrix box. In this example, we will not make use of “*” instead we will use the actual numbers. So the logic will remain the same as in the above example, the only change will be the output characters from * to numbers.
Desired Output of size 3:-
1 2 3
1 2 3
1 2 3
#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",col);
}
printf("\n");
}
return 0;
}
Output
Please enter the size of Square Box: 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5