Contact Learn C
Copy Program Share Program

Program 35:Number Pyramid

Program 35:
 
//       1
//      232
//     34543
//    4567654

#include<stdio.h>
main()
{
int i,j,left,right,k,rightcount,count,rows;
printf("Enter number of rows\n");
scanf("%d",&rows);
count=rows-1;
left=1;
right=0;

for(i=1;i<=rows;i++)
{//start of forloop
    for(k=1;k<=count;k++)
    {
        printf(" ");
    }
    for(j=i;j<=left;j++)
    {
        printf("%d",j);
    }
    left+=2;
       if(i!=1)
       {
               for(j=right;j>=i;j--)
             {
            printf("%d",j);
                 }
             
       }
        right+=2;
       printf("\n");
       count--;    
}//end of forloop
}

Explanation:
  1. The program starts with initializing
    • rows → Taken from user to print those many rows
    • i,j,k → used as variables.
    • left,right → for printing left and right part of triangle.
    • count → To controll spaces
  2. printf("Enter number of rows\n");
    scanf("%d",&rows);
    Taking number of rows as input from user 
  3. for(i=1;i<=rows;i++)
    {
    For iterating number of row times 
  4. for(k=1;k<=count;k++)
        {
            printf(" ");
        }
    To print spaces left side to achieve shape of pyramid.For example
    __1
    _232
    34543
    beside 1 we have two spaces and beside 2 we have one space and no space beside 3.this is for 3 rows.
  5. for(j=i;j<=left;j++)
        {
            printf("%d",j);
        }
        left+=2;
    To print left part of triangle.left+=2 is for incrementing the left by 2 times for each iteration. As if you look at the outputin Iteration 1: 1 is printed and in iteration2: 2,3 are printed  and so on
  6. if(i!=1)
           {
                   for(j=right;j>=i;j--)
                 {
                printf("%d",j);
                     }
                 
           }
            right+=2;
    To print right part of triangle which is skipped if i==1as we dont want to print any thing to the right side of 1 in first row.  right+=2 is for incrementing right by 2 for each iteration.Unlike left right is initialized to 0 as right side printing will start with even number.
    Number Pyramid right side
  7.   printf("\n");
            
    To start printing the numbers of pyramid in new line after finishing the iteration
  8. count--  is used to decrement the number of spaces to be printed beside the row to achieve the shape of pyramid.If the pyramid is for 4 rows then in 1st row 3 spaces will be printed and in 2nd row 2 spaces will be printed and so on till the end.

 Output:

Number Pyramid

1 comment:

  1. 3
    2 3 2
    1 2 3 2 1
    Can anyone help me for this pattern?

    ReplyDelete

Donate

Download App and Learn when ever you want

Get it on PlayStore
Get it on Amazon App Store
Get it on Aptoide