1.21.2012

Number triangle

Q. Write a c program for following number structure :
1
22
333
4444
55555
4444
333
22
1

Ans.

/*c program for above triangle structure using while*/
#include<stdio.h>
#include<conio.h>
int main()
{
 int num,n,r=1,c;
 printf("Enter triangle number : ");
 scanf("%d",&num);
 while(num >= r)
 {
  c=1;
  while(c <= r)
  {
    printf("%d",r);
    c++;
  }
  printf("\n");
  r++;
 }
 n=num-1;
 while(n >= 1)
 {
   c=1;
   while(c <= n)
   {
     printf("%d",n);
     c++;
   }
   printf("\n");
   n--;
 }
 getch();
 return 0;
}
OR
/*c program for above number triangle using for loop*/

#include<stdio.h>
#include<conio.h>
int main()
{
 int num,n,r,c;
 printf("Enter triangle number : ");
 scanf("%d",&num);
 for(r=1; r<=num; r++)
 {
   for(c=1; c<=r; c++)
      printf("%d",r);
   printf("\n");
 }
 for(n=num-1; n>=1; n--)
 {
   for(c=1; c<=n; c++)
      printf("%d",n);
   printf("\n");
 }
 return 0;
}


Output :-

Enter triangle number :5
1
22
333
4444
55555
4444
333
22
1

2 comments:

  1. The second program does not work correctly.

    ReplyDelete
  2. alternative program is not working properly,,,,!

    ReplyDelete