Program in C to Print Hollow Pyramid

Program in C to Print Hollow Pyramid

A hollow pyramid is a star pyramid where only the borders of the pyramid are printed, leaving the inside empty. This pattern is commonly used to practice nested loops, conditional statements, and alignment in C programming.

Understanding The Problem

The program should take the number of rows as input and print a pyramid where only the first and last stars of each row and the stars on the base are visible. The challenge is to correctly use conditional statements to decide when to print a star and when to print a space.

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 or spaces depending on the position in the row.
  • Move to a new line after each row.

Solution: Using Nested Loops with Conditionals

Nested loops along with conditional checks allow printing stars at the correct positions.

#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 for alignment. The second inner loop prints a star if it is the first or last position in the row or if it is the bottom row, otherwise it prints a space. This creates a hollow effect inside the pyramid.

Hollow Pyramid

FAQs

Q1: Can we use a different character for the hollow pyramid?
Yes, you can replace * with any symbol to create a hollow pyramid with that character.

Q2: Can this pattern be inverted?
Yes, by adjusting the loops and conditionals, you can create an inverted hollow pyramid.

Q3: Can the number of rows be decimal?
No, the number of rows must be an integer, as each row represents a discrete line of the pyramid.

Conclusion

This program demonstrates how to print a hollow pyramid using nested loops and conditional statements. By controlling spaces and selectively printing stars, you can create a visually appealing hollow pyramid. This concept can be extended to create hollow inverted pyramids, diamonds, and other star patterns.

References & Additional Resources

Scroll to Top