C++ Program to Print Inverted Hollow Star Pyramid Pattern

01/05/2024 0 By indiafreenotes

Creating an inverted hollow star pyramid pattern in C++ is an excellent exercise to deepen your understanding of loops and conditional statements. This pattern features an inverted pyramid where only the border of the pyramid is marked with stars (*), leaving the inside hollow or empty.

Example: Inverted Hollow Star Pyramid Pattern

This program will display an inverted hollow star pyramid based on the number of rows specified by the user. The top row will be completely filled with stars, and subsequent rows will only have stars at the borders, with the inner part being hollow until the last row which has just one star.

C++ Code:

#include <iostream>

using namespace std;

int main() {

    int rows;

    // User inputs the number of rows for the pyramid

    cout << “Enter the number of rows: “;

    cin >> rows;

    // Print the inverted hollow pyramid

    for (int i = rows; i > 0; –i) {

        // Print leading spaces

        for (int j = 0; j < rows – i; ++j) {

            cout << ” “;

        }

        // Print stars and hollow spaces

        for (int j = 1; j <= 2 * i – 1; ++j) {

            if (j == 1 || j == 2 * i – 1 || i == rows) {

                cout << “*”; // Print star at borders and top row

            } else {

                cout << ” “; // Print space inside the pyramid

            }

        }

        cout << endl;

    }

    return 0;

}

Explanation:

  1. Header and Namespace: The program includes <iostream> for input/output operations and uses the std
  2. Input: The user is prompted to enter the number of rows for the pyramid. This number determines the height of the inverted pyramid.
  3. Loop for Rows:
    • Outer Loop: Runs from the specified number of rows down to 1, handling each row of the pyramid.
    • First Inner Loop: Manages the spaces before the stars begin on each row. These spaces increase as you move to lower rows (which are visually higher in the inverted pyramid).
    • Second Inner Loop: Manages the printing of stars and hollow spaces. Stars are printed at the first and last positions (j == 1 or j == 2 * i – 1) and across the entire top row (i == rows). The rest is filled with spaces.

Program Output:

Assuming the user inputs 5 for the number of rows, the output will be:

*********

*     *

*   *

* *

*

This program uses a combination of loops and conditional logic to create an appealing pattern. Such exercises are useful for practicing how to manipulate output based on the location within the loops, a key skill in developing more complex algorithms and applications in C++.