Print a Hollow Triangle Star Pattern in C
To print a hollow triangle star pattern in C, we use nested loops to iterate through rows and columns while printing stars at the boundaries and spaces inside the triangle. The logic involves identifying the first and last star in each row and ensuring the base of the triangle is fully filled with stars.
Examples of Hollow Triangle Star Patterns
1. Printing a Basic Hollow Triangle
In this example, we will print a right-angled hollow triangle where the first and last stars in each row are displayed, and the last row is completely filled with stars.
main.c
#include <stdio.h>
int main() {
int n = 5; // Number of rows
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
// Print star at boundaries or last row
if (j == 1 || j == i || i == n) {
printf("* ");
} else {
printf(" ");
}
}
printf("\n");
}
return 0;
}
Explanation:
- We define
n
as the number of rows in the triangle. - The outer loop
for (int i = 1; i <= n; i++)
controls the number of rows. - The inner loop
for (int j = 1; j <= i; j++)
controls the number of columns. - We print
*
whenj == 1
(first column),j == i
(last column), or when it’s the last rowi == n
. - Otherwise, we print spaces
" "
for the hollow part. printf("\n")
moves to the next line after each row.
Output:
*
* *
* *
* *
* * * * *
2. Printing an Equilateral Hollow Triangle
In this example, we print an equilateral (pyramid-shaped) hollow triangle. The stars are printed at the boundary of each row, and the base row is fully filled.
main.c
#include <stdio.h>
int main() {
int n = 5; // Number of rows
for (int i = 1; i <= n; i++) {
// Print spaces for alignment
for (int j = 1; j <= n - i; j++) {
printf(" ");
}
// Print stars and spaces for hollow effect
for (int j = 1; j <= (2 * i - 1); j++) {
if (j == 1 || j == (2 * i - 1) || i == n) {
printf("*");
} else {
printf(" ");
}
}
printf("\n");
}
return 0;
}
Explanation:
- We define
n
as the number of rows. - The first inner loop prints spaces
" "
to align the triangle to the center. - The second inner loop prints stars and spaces inside the triangle.
- Stars are printed at the first column
j == 1
, the last columnj == (2 * i - 1)
, and the last rowi == n
. - Spaces
" "
are printed inside the triangle for the hollow effect. printf("\n")
moves to the next row after printing the pattern.
Output:
*
* *
* *
* *
*********
Conclusion
In this tutorial, we explored different ways to print a hollow triangle star pattern in C:
- Basic Hollow Triangle: Uses nested loops to print boundary stars and spaces inside.
- Equilateral Hollow Triangle: Uses additional space alignment and prints a centered pyramid pattern.