C Program to Print Hollow Pyramid Pattern

Introduction

A hollow pyramid pattern consists of stars (*) forming the boundary of the pyramid, while the inner part remains hollow (filled with spaces). This pattern helps beginners in C programming understand how to control the printing of specific positions using loops.

Problem Statement

Create a C program that:

  • Accepts the number of rows for the pyramid.
  • Prints a hollow pyramid pattern using stars (*).

Example:

  • Input: rows = 5
  • Output:
        *
       * *
      *   *
     *     *
    *********
    

Solution Steps

  1. Input the Number of Rows: The size determines how many rows the hollow pyramid will have.
  2. Use Nested Loops: The outer loop handles the rows, and the inner loops handle printing the stars and spaces.
  3. Display the Hollow Pyramid: Print stars on the boundary and spaces inside to create the hollow effect.

C Program

#include <stdio.h>

int main() {
    int i, j, rows;

    // Step 1: Accept the number of rows for the pyramid
    printf("Enter the number of rows: ");
    scanf("%d", &rows);

    // Step 2: Outer loop for the rows
    for (i = 1; i <= rows; i++) {
        // Step 3: Print spaces for alignment
        for (j = i; j < rows; j++) {
            printf(" ");
        }

        // Step 4: Print stars and spaces for the hollow pyramid
        for (j = 1; j <= (2 * i - 1); j++) {
            // Print star if it's the first row, last row, or at the boundary
            if (i == rows || j == 1 || j == (2 * i - 1)) {
                printf("*");
            } else {
                printf(" ");
            }
        }

        // Move to the next line after each row
        printf("\n");
    }

    return 0;
}

Explanation

Step 1: Input Number of Rows

  • The program starts by taking input from the user, which defines the number of rows for the hollow pyramid.

Step 2: Outer Loop for Rows

  • The outer loop runs from 1 to rows and controls the number of rows printed.

Step 3: Print Spaces for Alignment

  • The first inner loop prints spaces to align the stars properly for the pyramid shape. The number of spaces decreases as you move down the rows.

Step 4: Print Stars and Spaces

  • The second inner loop prints stars (*) and spaces to create the hollow effect.
    • Stars are printed at the boundary (first column, last column of each row, and on the last row).
    • For positions inside the pyramid, spaces are printed to make it hollow.

Output Example

For rows = 5, the output will be:

    *
   * *
  *   *
 *     *
*********

For rows = 6, the output will be:

     *
    * *
   *   *
  *     *
 *       *
***********

Conclusion

This C program prints a hollow pyramid using stars (*). The pattern is created by printing stars at the boundary of the pyramid and spaces inside. This exercise is useful for learning how to control loops and conditional printing in C.

Comments