Lets write a C program to draw / print / display a pyramid / triangle formed from stars, using nested for loop.
Related Read:
Nested For Loop In C Programming Language
C Program To Draw Pyramid of Stars, using While Loop
Page Contents
Expected Output for the Input
User Input:
Enter no of rows of Pyramid
5
Output:
* *** ***** ******* *********
Pyramid With 20 Rows
Video Tutorial: C Program To Draw Pyramid of Stars, using For Loop
Logic To Draw Pyramid of Stars, using For Loop
If num = 5;
First Iteration of outer for loop
row = 1;
1st inner for loop
condition:
num – row;
= 5 – 1
= 4
Four spaces gets printed.
2st inner for loop
condition:
2 * row – 1;
= 2 * 1 – 1;
= 2 – 1
= 1
One star gets printed.
Second Iteration of outer for loop
row = 2;
1st inner for loop
condition:
num – row;
= 5 – 2
= 3
Three spaces gets printed.
2st inner for loop
condition:
2 * row – 1;
= 2 * 2 – 1;
= 4 – 1
= 3
Three stars gets printed.
Third Iteration of outer for loop
row = 3;
1st inner for loop
condition:
num – row;
= 5 – 3
= 2
Two spaces gets printed.
2st inner for loop
condition:
2 * row – 1;
= 2 * 3 – 1;
= 6 – 1
= 5
Five stars gets printed.
Forth Iteration of outer for loop
row = 4;
1st inner for loop
condition:
num – row;
= 5 – 4
= 1
One space gets printed.
2st inner for loop
condition:
2 * row – 1;
= 2 * 4 – 1;
= 8 – 1
= 7
Seven stars gets printed.
Fifth Iteration of outer for loop
row = 5;
1st inner for loop
condition:
num – row;
= 5 – 5
= 0
Zero space gets printed.
2st inner for loop
condition:
2 * row – 1;
= 2 * 5 – 1;
= 10 – 1
= 9
Nine stars gets printed.
Source Code: C Program To Draw Pyramid of Stars, using For Loop
- #include<stdio.h>
- int main()
- {
- int num, row, col, space;
- printf("Enter no of rows of Pyramid\n");
- scanf("%d", &num);
- for(row = 1; row <= num; row++)
- {
- for(space = 1; space <= (num-row); space++)
- {
- printf(" ");
- }
- for(col = 1; col <= (2*row-1); col++)
- {
- printf("*");
- }
- printf("\n");
- }
- 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