Lets write a C program to draw / print / display a pyramid / triangle formed from Decimal numbers(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), using while loop.
Related Read:
Nested While Loop: C Program
C Program To Draw Pyramid of Stars, using While Loop
C Program To Draw Pyramid of Alphabets, using While Loop
Page Contents
Expected Output for the Input
User Input:
Enter the maximum no of rows for Pyramid
5
Output:
0
123
45678
9012345
678901234
Pyramid With 20 Rows
Video Tutorial: C Program To Draw Pyramid of Numbers, using While Loop
Logic To Draw Pyramid of Numbers, using While Loop
We ask the user to enter the maximum number of rows for the pyramid and store it inside the address of variable num. We declare and initialize a variable row to 1(indicating first row of the pyramid).
In the outer while loop we check if row is less than or equal to num. For each iteration of the while loop we increment the value of row by 1. So the row value will have the row number i.e., for each iteration of the outer while loop we select row one by one (to print the numbers in that selected row).
Inside first inner while loop we print the adequate number of space for each row. Inside the second inner while loop we actually print the numbers needed for each row.
At the end, result will be a pyramid with the number of rows as input by the user.
Source Code: C Program To Draw Pyramid of Numbers, using While Loop
#include < stdio.h >
int main()
{
int num, i, row = 1, number = 0;
printf("Enter the maximum no of rows for Pyramid\n");
scanf("%d", &num);
while(row <= num)
{
i = 0;
while(i <= (num-row))
{
printf(" ");
i++;
}
i = 0;
while(i < (2*row-1))
{
printf("%d", number);
if(number == 9)
number = 0;
else
number++;
i++;
}
printf("\n");
row++;
}
return 0;
}
Output
Enter the maximum no of rows for Pyramid
14
0
123
45678
9012345
678901234
56789012345
6789012345678
901234567890123
45678901234567890
1234567890123456789
012345678901234567890
12345678901234567890123
4567890123456789012345678
901234567890123456789012345
For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List
For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert