Print a Hollow Pyramid Star Pattern in C
To print a hollow pyramid star pattern in C, we use nested loops to print stars (*
) in a pyramid shape while leaving spaces inside to create a hollow effect. The outer loop controls the rows, and the inner loops manage spaces and star placements.
Examples to Print Hollow Pyramid
1. Basic Hollow Pyramid Pattern
In this example, we will print a basic hollow pyramid where the first and last stars of each row are printed, while spaces fill the inside of the pyramid.
main.c
#include <stdio.h>
int main() {
int rows = 5;
for (int i = 1; i <= rows; i++) {
// Print leading spaces
for (int j = i; j < rows; j++) {
printf(" ");
}
// Print stars and spaces
for (int j = 1; j <= (2 * i - 1); j++) {
if (j == 1 || j == (2 * i - 1) || i == rows) {
printf("*");
} else {
printf(" ");
}
}
printf("\n");
}
return 0;
}
Explanation:
- We declare an integer variable
rows
and set it to 5. - The outer loop (
i
) runs from 1 torows
, controlling the pyramid height. - The first inner loop (
j
) prints spaces before the stars to align the pyramid. - The second inner loop (
j
) prints stars at the beginning and end of each row, and spaces in between. - On the last row, we print all stars to form the pyramid base.
- Each row ends with
printf("\n")
to move to the next line.
Output:
*
* *
* *
* *
*********
2. Hollow Pyramid with User Input
In this example, we take the number of rows as input from the user to make the pattern dynamic.
main.c
#include <stdio.h>
int main() {
int rows;
printf("Enter number of rows: ");
scanf("%d", &rows);
for (int i = 1; i <= rows; i++) {
for (int j = i; j < rows; j++) {
printf(" ");
}
for (int j = 1; j <= (2 * i - 1); j++) {
if (j == 1 || j == (2 * i - 1) || i == rows) {
printf("*");
} else {
printf(" ");
}
}
printf("\n");
}
return 0;
}
Explanation:
- We declare an integer
rows
and prompt the user to enter its value usingscanf()
. - The outer loop (
i
) controls the row iteration. - The first inner loop prints spaces before stars to form the pyramid shape.
- The second inner loop prints stars at the edges and spaces in between, creating the hollow effect.
- On the last row, all positions are filled with stars.
- The output varies based on user input, making the program flexible.
Example Output:
Enter number of rows: 6
*
* *
* *
* *
* *
***********
Conclusion
In this tutorial, we learned how to print a hollow pyramid star pattern in C using nested loops. We covered:
- Basic Hollow Pyramid: A static pyramid of fixed size.
- Hollow Pyramid with User Input: Dynamic pattern based on user input.
The key concept is using nested loops to print stars and spaces, ensuring only the outer boundary stars are printed while leaving the inside hollow.