Generate an inverted full pyramid pattern with stars in C++
In this shot, we will discuss how to make an inverted full pyramid pattern with stars in C++.
Approach
We will use nested loops to generate an inverted full pyramid pattern. A nested loop means a loop that calls another loop.
Let’s look at the below image to understand this better.
We used the for loop with the decrement operator to make an inverted full pyramid pattern as shown in the image above.
Code
Let’s see the code snippet below to understand this better.
#include <iostream>using namespace std;int main() {int number;cin >> number;for (int i=number; i >= 1; i--){for (int j=number; j > i; j--){cout << " ";}for (int k=1; k < i*2; k++){cout << "*";}cout << endl;}return 0;}
Enter the input below
Please enter a number in the input section to determine the number of rows the inverted pyramid will have.
Explanation
-
In line 5, we initialize a
numbervariable. -
In line 6, we take the input as
number. -
In line 7, we initialize an outer
forloop where we have given conditions to run the loop untili>=1and a decrement operator, so as to print an inverted pyramid. -
From lines 9 to 12, we initialize an inner
forloop where we have given conditions to run the loop untilj>ito print the( ). -
From lines 13 to 16, we initialize another inner
forloop to print*. -
In line 17, we use a next line character so that the
*or( )gets printed from the next line onwards.
In this way, we have learned to generate an inverted full pyramid pattern with stars in C++.
Note: This pattern can also be made with numbers, alphabets, or any other characters.