C Program To Draw Pyramid of Stars, using While Loop


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

Expected Output for the Input

User Input:
Enter no of rows of Pyramid
5

Output:

    
     *
    ***
   *****
  *******
 *********

Pyramid With 20 Rows
pyramid of stars

Video Tutorial: C Program To Draw Pyramid of Stars, using While Loop


[youtube https://www.youtube.com/watch?v=pwLx0cELxY4]

YouTube Link: https://www.youtube.com/watch?v=pwLx0cELxY4 [Watch the Video In Full Screen.]

Logic 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.

Source Code: C Program To Draw Pyramid of Stars, using While Loop

#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

Leave a Reply

Your email address will not be published. Required fields are marked *