Program 35:
Output:
// 1 // 232 // 34543 // 4567654 #include<stdio.h>Explanation: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 }
- 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
printf("Enter number of rows\n"); scanf("%d",&rows);
Taking number of rows as input from userfor(i=1;i<=rows;i++) {
For iterating number of row timesfor(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.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 onif(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.printf("\n");
To start printing the numbers of pyramid in new line after finishing the iteration- 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: