4
34
234
1234
For this pattern we have to take care about three things
The pattern requires three loops
In line no.1 we need to print 3 spaces and value is 434
234
1234
For this pattern we have to take care about three things
- We need to print 4 lines
- We need to print required spaces in lines
- We need to print the values.
The pattern requires three loops
- An outer loop to loop 4 times.
- An inner loop to control the no. of spaces needed to be printed in each line.
- An inner loop to print certain after spaces in each line.
In line no.2 we need to print 2 spaces and value 3 and 4.
So we see that no. of spaces in each line decrease and finally become zero.
The number of digits in each line increases.
we can also see that spaces + digits in each line are 4 and remain 4 for all the lines
Line No. No. of Spaces No. of Values
1 3 1 (3+1=4)
2 2 2 (2+2=4)
3 1 3 (3+1=4)
4 0 4 (4+0=4)
Outer loop variable i should iterate 4 times. As we need first digit in first line 4 we can start i=4 and then decrement it and make j dependent on i. (although the same pattern can be printed in number of ways)
for(i=4;i>=1;i--)
first inner loop is controlling the number of spaces in each line. Its number of times it iterates should reduces. As we noted that no. of digits + no. of spaces is constant = 4 for this pattern, we can make this loop dependent on i also. As i starts from 4 and number of spaces should be 3 for 1st line space =4-1 each time and decrement till 1 or the other way start from 1 and go upto i-1. For line 2 i's value will become 3 and 3-1 will become 2 and we need tw spaces to be printed as desired.
for(j=i-1;j>=1;j--)
printf(" ");
for printing value we need a another loop. For first line this loop shall only print 4. Then for second line it should print 3 and 4. We can recognize that this loop starts from i's value and go till 4 for each line because each line is printing as its last value.
for(k=i;k<=4;k++)
printf("%d",&k);
#include<stdio.h>
int main()
{
int i, j, k;
for(i=4;i>=1;i--)
{
for(j=i-1;j>=1;j--)
{
printf(" ");
}
for(k=i;k<=4;k++)
{
printf("%d",k);
}
printf("\n");
}
return 0;
}
No comments:
Post a Comment