Program in C to Print Hollow Triangle of Stars

Program in C to Print Hollow Triangle of Stars

A hollow triangle of stars is a triangular pattern where only the borders of the triangle are printed, leaving the inside empty. This pattern helps learners understand nested loops, conditional statements, and proper alignment in C.

Understanding The Problem

The program should take the number of rows as input and print a triangle where only the first and last stars of each row and the stars on the base row are visible. Correct use of nested loops and conditionals is essential to create the hollow effect.

Steps to Solve the Problem:

  • Take the number of rows from the user.
  • Use an outer loop to iterate through each row.
  • Use an inner loop to print spaces for alignment.
  • Use another inner loop to print stars on borders and spaces inside.
  • Move to a new line after each row.

Solution: Using Nested Loops with Conditionals

Nested loops combined with conditional checks allow printing stars at the correct positions while leaving the inside hollow.

#include <stdio.h>

int main() {

    int rows;

    printf("Enter number of rows: ");
    scanf("%d", &rows);

    for(int i = 1; i <= rows; i++) {

        // Print leading spaces
        for(int j = 1; j <= rows - i; j++) {
            printf(" ");
        }

        // Print stars and spaces inside the row
        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;

}

In this program, the outer loop controls the rows. The first inner loop prints spaces to center the triangle. The second inner loop prints stars at the edges or on the bottom row, while printing spaces elsewhere to maintain the hollow effect.

Hollow Triangle of Stars

FAQs

Q1: Can we use a character other than *?
Yes, you can replace * with any symbol to print a hollow triangle with that character.

Q2: Can we invert the hollow triangle?
Yes, by adjusting the loops and conditionals, an inverted hollow triangle can be printed.

Q3: Can the number of rows be decimal?
No, the number of rows must be an integer because each row corresponds to discrete lines in the triangle.

Conclusion

This program demonstrates how to print a hollow triangle of stars using nested loops and conditional statements. By controlling which positions contain stars and which contain spaces, a visually appealing hollow triangle is created. This logic can be extended to hollow pyramids, diamonds, and other geometric patterns.

References & Additional Resources

Scroll to Top