How to generate a hollow inverted half pyramid pattern in C++

In this shot, we will discuss how to make a hollow inverted half pyramid pattern using stars in C++.

Approach

We will use a nested loop and a while loop to generate this pattern. A nested loop refers to a loop that contains another loop.

Below is the visual of the hollow inverted half pyramid.

Hollow Inverted Half Pyramid Pattern

To generate a hollow inverted half pyramid pattern in C++, we use one for loop to print the * in the first line. Then, we use an outer for loop, where we use a decrement operator. We use the decrement operator to generate an inverted pattern to print * and a blank space.

In the while loop, we add a condition in our code so that our pyramid is hollow from the inside.

Code

#include <iostream>
using namespace std;
int main() {
int number, i, j, h=0;
cin >> number;
for (i = 0; i < number; i++)
cout << "* " ;
for (i = number; i >= 1; --i)
{
for (j = 0; j < number - i; ++j){
while (h != (2 * i - 1))
{
if (h == 0 || h == 2 * i - 2)
cout << "*" ;
else
cout << " " ;
h++;
}
}
h = 0;
cout << endl;
}
return 0;
}

Enter the input below

Please enter a number in the input section above.

Explanation

  • In line 5, we initialize the variables number, i, j, and h.

  • In line 6, we take the input as number.

  • In line 8, we initialize a for loop, where we give a condition to run the loop number times to print *. This will print the * in the first line.

  • In line 11, we initialize another outer for loop, where we give a condition to run the loop each time it is greater than or equal to 1.

  • In line 13, we initialize an inner for loop, where we give conditions to run the loop for number - 1 times, as we have already printed the first line in the above step.

  • In line 14, we initialize a while loop, where we give conditions to print * or accordingly.

  • In line 16, we give a condition to print * and a blank space. The condition will print * at the edges of the pyramid and print a blank space inside the pyramid.

  • In line 24, we print a next line character. This is done so that the star or blank space gets printed now from the next line onwards.

This way, we can make a hollow inverted half pyramid pattern using loops in C++.

This pattern can also be made using numbers, alphabets, or any other characters.