Lets write a C program to draw / print / display a pyramid / triangle formed from stars, using while loop.
Related Read:
while loop in C programming
Nested While Loop: C Program
Page Contents
User Input:
Enter no of rows of Pyramid
5
Output:
* *** ***** ******* *********
Pyramid With 20 Rows
Video Tutorial: C Program To Draw Pyramid of Stars, 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 count to 1(indicating first row of the pyramid).
In the outer while loop we check if count is less than or equal to num. For each iteration of the while loop we increment the value of count by 1. So the count 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 stars).
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 stars needed for each row.
At the end the result will be a pyramid with the number of rows as input by the user.
#include<stdio.h> int main() { int num, count = 1, i; printf("Enter no of rows of Pyramid\n"); scanf("%d", &num); while(count <= num) { i = 0; while( i <= (num - count) ) { printf(" "); i++; } i = 0; while(i < (2*count-1)) { printf("*"); i++; } printf("\n"); count++; } return 0; }
Output 1:
Enter no of rows of Pyramid
5
* *** ***** ******* *********
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