Print a Pyramid Star Pattern in C
To print a pyramid star pattern in C, we use nested loops. The outer loop controls the number of rows, while the inner loops handle spaces and stars to form a symmetrical pyramid shape.
Examples of Pyramid Star Patterns
1. Simple Pyramid Star Pattern
In this example, we will print a pyramid pattern where each row has an increasing number of stars, centered using spaces.
main.c
</>
Copy
#include <stdio.h>
int main() {
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= rows - i; j++) {
printf(" ");
}
for (int k = 1; k <= 2 * i - 1; k++) {
printf("*");
}
printf("\n");
}
return 0;
}
Explanation:
- We declare
rows
as 5, which determines the pyramid height. - The outer loop (
i
) runs from 1 torows
to print each row. - The first inner loop prints spaces before the stars to center-align the pyramid.
- The second inner loop prints
(2 * i - 1)
stars to form the pyramid shape. - The
printf("\n")
moves to the next row after printing one complete line.
Output:
*
***
*****
*******
*********
2. Inverted Pyramid Star Pattern
In this example, we will print an inverted pyramid where the number of stars decreases in each row.
main.c
</>
Copy
#include <stdio.h>
int main() {
int rows = 5;
for (int i = rows; i >= 1; i--) {
for (int j = 0; j < rows - i; j++) {
printf(" ");
}
for (int k = 0; k < (2 * i - 1); k++) {
printf("*");
}
printf("\n");
}
return 0;
}
Explanation:
- We declare
rows
as 5, which defines the height of the inverted pyramid. - The outer loop (
i
) starts fromrows
and decrements to 1. - The first inner loop prints spaces to center-align the stars.
- The second inner loop prints
(2 * i - 1)
stars, reducing in each row. printf("\n")
moves to the next row.
Output:
*********
*******
*****
***
*
3. Hollow Pyramid Star Pattern
In this example, we will print a pyramid where only the outer boundary stars are visible, making it hollow inside.
main.c
</>
Copy
#include <stdio.h>
int main() {
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= rows - i; j++) {
printf(" ");
}
for (int k = 1; k <= (2 * i - 1); k++) {
if (k == 1 || k == (2 * i - 1) || i == rows)
printf("*");
else
printf(" ");
}
printf("\n");
}
return 0;
}
Explanation:
- We declare
rows
as 5, setting the pyramid height. - The outer loop controls the number of rows.
- The first inner loop prints spaces to align the stars properly.
- The second inner loop prints stars at the start, end, and last row while printing spaces inside.
- The condition
if (k == 1 || k == (2 * i - 1) || i == rows)
ensures stars are printed at boundaries.
Output:
*
* *
* *
* *
*********
Conclusion
In this tutorial, we explored different pyramid star patterns in C using nested loops:
- Simple Pyramid: A standard symmetrical pyramid.
- Inverted Pyramid: A flipped version where rows decrease.
- Hollow Pyramid: A pyramid with only boundary stars.