Pattern printing problems
In this kind of problems we are asked to print any pattern using any special characters like '@' or '#' or '*'
or even using numbers.
Topic here says how to print patterns like
a)right angled triangle
*
* *
* * *
* * * *
* * * * *
b) reverse of pattern shown above reverse right angled triangle
* * * * *
* * * *
* * *
* *
*
c)A Complete triangle
*
* * *
* * * *
* * * * *
First let us see right angled triangle
- Consider the pattern and assign numbers for each row and column
1 | 2 | 3 | 4 | 5 | |
1 | * | ||||
2 | * | * | |||
3 | * | * | * | ||
4 | * | * | * | * | |
5 | * | * | * | * | * |
i | j |
1 | 1 |
2 | 2 |
3 | 3 |
4 | 4 |
5 | 5 |
Using above above diagram we can conclude that If we are in "i"th row then we print "i" asterisks .
So out C code goes like this
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
{
printf("* ");
}
printf("\n");// '\n' because we need a new line after i symbols
}
NOW we see reverse right angled triangle.
1 | 2 | 3 | 4 | 5 | |
1 | * | * | * | * | * |
2 | * | * | * | * | |
3 | * | * | * | ||
4 | * | * | |||
5 | * |
Explanation:
By seeing table we can understand that if we are in "i" th row we need to print n-i+1 number of symbols. where n is number of rows.
I | J |
1 | 5 |
2 | 4 |
3 | 3 |
4 | 1 |
5 | 1 |
here row number is n=5
For i=1 We get 5-1+1 hence j is 5
For i=2 we get 5-2+1 hence j is 4
in similar way we got the whole table, Code snippet for this pattern is
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n-i+1;j++)
{
printf("* ");
}
printf("\n");// '\n' because we need a new line after i symbols
}
Complete triangle
1 | 2 | 3 | 4 | 5 | |
1 | blank | blank | * | blank | blank |
2 | blank | * | * | * | blank |
3 | * | * | * | * | * |
I | number of stars | blanks |
1 | 1 | 2 |
2 | 3 | 1 |
3 | 5 | 0 |
s=n;
for (int i = 1; i <= n; i++) // Loop to print rows
{
for (int j = 1; j< s; j++) // Loop to print spaces in a row
printf(" ");
s--;
for (j = 1; j <= 2*i - 1; j++) // Loop to print stars in a row
printf("*");
printf("\n");
}
Hope This Helps......
Happy coding....