In this shot, we will discuss how to make a hollow inverted full pyramid pattern using stars in C++.
A nested loop refers to a loop inside another loop. We will use a nested loop to make the inverted hollow full pyramid pattern in C++.
Let’s look at an image of the pattern that we want to generate.
We use the for
loop and the while
loop to generate this inverted hollow full pyramid pattern. In the loop, we give conditions to print space and star in each row.
Let’s look at the code below to understand this better.
#include <iostream> using namespace std; int main() { int number; cin >> number; for (int i = 1; i <= number; i++) { for (int j = 1; j < i; j++) { cout << " "; } for (int j = 1; j <= (number * 2 - (2 * i - 1)); j++) { if (i == 1 || j == 1 || j == (number * 2 - (2 * i - 1))) cout << "*" ; else cout << " " ; } cout << endl ; } return 0; }
Enter the input below
Please enter a number above to generate an output.
In line 5, we initialize the variable number
.
In line 6, we take the input as number
.
In line 7, we initialize an outer for
loop. Here, we have given a condition to run the loop for number
times.
In line 9, we initialize an inner for
loop. Here, we have given conditions to run the loop for i
times to print space.
From lines 13 to 19, we initialize the for
loop. Here, we have given if-else conditions to print *
or space in each row.
In line 20, we print a next line character. We do this so that the *
or space gets printed from the next line onwards.
In this way, we can use loops to make an inverted hollow full pyramid pattern in C++.
RELATED TAGS
CONTRIBUTOR
View all Courses