C Program to Print Number Pyramid Pattern
Generate Following Pattern of Pyramid
Program :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include<stdio.h> #include<conio.h> int main() { int i, num, j, xpos = 30, ypos = 10; clrscr(); printf("Enter n (between 2 & 9) : "); scanf("%d", &num); for (i = 1; i <= num; i++) { gotoxy(xpos, ypos); for (j = 1; j <= i; j++) printf("%d ", i); xpos = xpos - 1; ypos++; } return (0); } |
Output :
1 2 3 4 5 6 7 8 9 10 |
Enter n (between 2 & 9) : 9 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9 |
Explain ?
1 |
gotoxy(x,y); |
- Gotoxy : interpret it as “goto x y”
- Moves Cursor Position to Co-Ordinate (x,y)
- gotoxy(10,40) : moves Cursor Position to Co-ordinate (10,40)
1 2 |
x=x-1; y++; |
- In Each Iteration we are moving downward so increment “y”
- For each new Iteration we are starting from beginning but one co-ordinate back so decrement x
1 2 |
for (j = 1; j <= i; j++) printf("%d ", i); |
- Nested Loop Used to Print All the Numbers in Particular Line . i.e in the third line i = 3 so j will print values 3 times .