In this shot, we will discuss how to make a hollow half pyramid pattern with stars in C++.
Click here to learn how to generate an inverted half pyramid pattern with stars in C++ and here to learn how to generate a half pyramid pattern with stars in C++.
To generate this pattern, we use a nested loop. A nested loop means loop inside another loop.
Let’s look at the image below to understand what our hollow half pyramid will look like.
In this hollow half pyramid pattern, the *
will print on the edges of the pyramid and it will be hollow inside.
Let’s look at the code snippet.
#include <iostream>using namespace std;int main() {int number;cin >> number;for (int i=1; i<=number; i++){for (int j=1; j<=number; j++){if (j==1 || i==j || i==number )cout << " * ";elsecout << " ";}cout << endl;}return 0;}
Enter the input below
(Please enter a number in the input section.)
In line 5, we initialize a number
variable.
In line 6, we take the input as number
.
In line 7, we initialize an outer for loop, where we give a condition to run the loop number
times.
In line 9, we initialize an inner for loop, where we give conditions to run the loop number
times.
In line 11, we give a condition to print *
. Otherwise, it will print blank space.
In line 16, we print a next line character. This is done so that the star or blank space gets printed now from the next line onwards.
In this way, we can use loops to make a hollow half pyramid pattern in C++.
Note: Numbers, alphabets, or any other characters can also be used to make this pattern.