C program for pyramid/triangle number pattern 22
This program is to print pyramid/triangle number pattern 22 in C.
1
121
12321
1234321
123454321
12345654321
1234567654321
Dry Run of the Program
Let us take no of lines ‘n’ = 3
Outer For Loop 1st iteration
for(i=1;i<=n;i++ ) i.e. for(i=1;1<=3;i++ )
1st Inner For Loop 1st iteration
for(j=1;j<=n-i;j++) i.e. for(j=1;1<=2;j++)
print(” “) // space
1st Inner For Loop 2nd iteration
for(j=2;j<=n-i;j++) i.e. for(j=2;2<=2;j++)
print(” “) // space
2nd Inner For Loop 1st iteration
for(j=1;j<=i;j++) i.e. for(j=1;1<=1;j++)
printf(“%d”,j); i.e. print 1 //leaving 2 spaces from left
3rd Inner For Loop is not executed as j=i-1(i.e. j=0) 0>=1
printf(“\n”) i.e. Leave a line
Outer For Loop 2nd iteration
for(i=2;i<=n;i++ ) i.e. for(i=2;2<=3;i++ )
1st Inner For Loop 1st iteration
for(j=1;j<=n-i;j++) i.e. for(j=1;1<=1;j++)
print(” “) // space
2nd Inner For Loop 1st iteration
for(j=1;j<=i;j++) i.e. for(j=1;1<=2;j++)
printf(“%d”,j); i.e. print 1 //leaving 1 space from left
2nd Inner For Loop 2nd iteration
for(j=2;j<=i;j++) i.e. for(j=2;2<=2;j++)
printf(“%d”,j); i.e. print 2 //
Output till now
__1
_12
3rd Inner For Loop 1st iteration
for(j=i-1;j>=1;j–) i.e. for(j=1;1>=1;j–)
printf(“%d”,j) i.e. print 1
Output till now
__1
_121
printf(“\n”) i.e. Leave a line
Outer For Loop 3rd iteration
for(i=3;i<=n;i++ ) i.e. for(i=3;3<=3;i++ )
1st Inner For Loop is not executed as j(1) is not j(1)<=0
2nd Inner For Loop 1st iteration
for(j=1;j<=i;j++) i.e. for(j=1;1<=3;j++)
printf(“%d”,j); i.e. print 1
2nd Inner For Loop 2nd iteration
for(j=2;j<=i;j++) i.e. for(j=2;2<=3;j++)
printf(“%d”,j); i.e. print 2 //
2nd Inner For Loop 3rd iteration
for(j=3;j<=i;j++) i.e. for(j=3;3<=3;j++)
printf(“%d”,j); i.e. print 3 //
Output till now
__1
_121_
123
3rd Inner For Loop 1st iteration
for(j=i-1;j>=1;j–) i.e. for(j=2;2>=1;j–)
printf(“%d”,j) i.e. print 2
3rd Inner For Loop 2nd iteration
for(j=i-1;j>=1;j–) i.e. for(j=1;1>=1;j–)
printf(“%d”,j) i.e. print 1
Final Output
__1__
_121_
12321
Program
#include<stdio.h> void main() { int i,n,j; printf("Enter the no of lines\n"); scanf("%d",&n); for(i=1;i<=n;i++) { for(j=1;j<=n-i;j++) { printf(" "); } for(j=1;j<=i;j++) { printf("%d",j); } for(j=i-1;j>=1;j--) { printf("%d",j); } printf("\n"); } }