In this article, I will show you, How to write a C program to print pyramid star pattern or equilateral triangle star pattern series of n rows using for loop. How to print pyramid star pattern in C programming. Here, one thing is important to know that the rows of the triangle.
Logic to print pyramid star pattern ( equilateral triangle star pattern)
- Enter the row value for the equilateral triangle.
- Here I have used three loops one is the outer loop to change the line and two inner loops to print star and space.
- The outer loop iterate row times and print a newline after completing the inner loop.
- If you will look at the design carefully, then you will find that the N rows pyramid contains (2*x)-1) star and (N-x) spaces (where N is the row number and x is the current row number).
- So to print the space inner loop iterate x to N times and to print the star second inner loop iterate 1 to (2*x)-1) times.
See the, C program to print pyramid star pattern:
#include <stdio.h> int main() { int x = 0,y = 0; unsigned int rows = 0; printf("Enter the number of rows = "); scanf("%u",&rows); for(x=1; x<=rows; ++x) { // Print spaces for(y=x; y<=rows; ++y) { printf(" "); } // Print star/ for(y =1; y<=((2*x)-1); ++y) { printf("*"); } // Print new line printf("\n"); } return 0; }
Output:
Code Analysis:
It asks the user to enter the row for the pyramid (equilateral triangle).
printf("Enter the number of rows = "); scanf("%u",&rows);
first, inner loop print space x to (N-1) times.
// Print spaces for(y=x; y<rows; ++y) { printf(" "); }
Second inner loop print star and it will iterate 1 to (2x-1) times.
// Print star for(y =1; y<=((2*x)-1); ++y) { printf("*"); }
The outer loop print the newline after each iteration of the inner loops.
Recommended Post:
- C program to Print Square Star Pattern.
- C program to print the mirrored right triangle star pattern.
- print hollow mirrored right triangle star pattern.
- How to use for loop in C.
- Use of if condition in C programs.
- File handling in C.
- C format specifiers.
- 100 C interview Questions.
- Pointer in C.
- Use of do-while in C.
- How to use fgetc in C?
- How to use fputc in C?