Let us suppose we have to draw a pattern like this-
***1***
**121**
*12321*
1234321
Whatever be the pattern the method remains same.
Let us take an even complex pattern -

All patterns can be grouped into number of triangles as shown above.
For
***1***
**121**
*12321*
1234321 pattern we have 4 sub triangles
1.
***
**
*
2.
1
12
123
1234
3.
1
21
321
4.
***
**
*
We will write a master for loop for 4 times i.e equal to the number of rows we have to print and insite that we will run for loops 4 times for each triangle.
If the pyramid becomes inverted after half then we will have to have 2 mater for loops.
#include<stdio.h>
int main()
{
for (int i = 1; i <= 4; i++) //for 4 horizontal lines
{
for (int j = 4; j-i > 0; j--) //as we go down we have to print one star lesser
printf("*");
for (int k = 1; k <= i; k++) //as we go down we have to print one more digit in increasing order
printf("%d", k);
for (int m = i; m > 1; m--) /*except for first line we have to print one digit less than the line number */'
printf("%d", m-1);
for (int l = 4; l - i >= 1; l--)
printf("*");
printf("\n");
}
return 0;
}
***1***
**121**
*12321*
1234321
Whatever be the pattern the method remains same.
Let us take an even complex pattern -
1 121 123211234321 12321 121 1
All patterns can be grouped into number of triangles as shown above.
For
***1***
**121**
*12321*
1234321 pattern we have 4 sub triangles
1.
***
**
*
2.
1
12
123
1234
3.
1
21
321
4.
***
**
*
We will write a master for loop for 4 times i.e equal to the number of rows we have to print and insite that we will run for loops 4 times for each triangle.
If the pyramid becomes inverted after half then we will have to have 2 mater for loops.
#include<stdio.h>
int main()
{
for (int i = 1; i <= 4; i++) //for 4 horizontal lines
{
for (int j = 4; j-i > 0; j--) //as we go down we have to print one star lesser
printf("*");
for (int k = 1; k <= i; k++) //as we go down we have to print one more digit in increasing order
printf("%d", k);
for (int m = i; m > 1; m--) /*except for first line we have to print one digit less than the line number */'
printf("%d", m-1);
for (int l = 4; l - i >= 1; l--)
printf("*");
printf("\n");
}
return 0;
}
No comments:
Post a Comment