The trick to solve it is, you have to imagine the pyramid to be composed of 3 seperate triangles.see image(sorry for bad pic)
It is upon you how many levels you want in your pyramid,for eg the pyramid in pic is 3 layerd.ie 1 121 12321
so for each layer you have to use 3 triangles which make up the pyramid,So you have to use following 4 loops
to implement the 4 ideas
1.Total number of  Rows
You use loop to tell how many layers you want.ie say no of layer is n (eq int n=3)
for( i=1;i<=n;i++)
{
2.First triangle is blank space
you have to use a loop to populate the blank space:
for( j=1;j<=(n-i);j++)
printf(” “);
3.Second triangle is made up of sequence which increases in value
You have to use another loop to create the sequence  which increases
for(k=1;k<=i;k++)
printf(“%d”,k);
4.Third triangle is made up of sequence which decreases in value
So you have to use yet another loop to decrease the value:
for(l=(i-1);l>=1;l–)
printf(“%d”,l);
}
Here is the code you can try
#include<stdio.h> void main() { int i,j,n,k,l; for(i=1;i<=n;i++) { for(j=1;j<=(n-i);j++) printf(" "); for(k=1;k<=i;k++)
printf("%d",k); for(l=(i-1);l>=1;l--) printf("%d",l);
printf("n"); } }
No comments:
Post a Comment