About Me

My photo
Raipur, Chhattisgarh, India
Hi , I am Amit Thakur. I have worked as a QA Engineer for two years and as a Java Developer for one year in NIHILENT TECHNOLOGIES PVT. LTD., Pune.Currently I am working as DEAN (Research & Development) in Bhilai Institute of Technology, Raipur.

Tuesday, September 3, 2013

C Program to Print Number Pyramid Pattern

Generate Following Pattern of Pyramid
Program :
#include
#include
void main()
{
int i,n,j,x=30,y=10;
clrscr();

printf("Enter n (between 2 & 9) : ");
scanf("%d",&n);

 for(i=1;i<=n;i++)
 {
    gotoxy(x,y);
      for(j=1;j<=i;j++)
         printf("%d ",i);
    x=x-1;
    y++;
 }
getch();
}

Output :
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 ?
gotoxy(x,y);
  •  Goto xy : 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)
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
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 .

No comments: