Generate an inverted half pyramid pattern with stars in C++
In this shot, we will discuss how to make an inverted half pyramid pattern with stars in C++.
Solution approach
We will use a nested loop to generate an inverted half pyramid pattern.
Let’s look at the image below to understand how our pattern will look.
In an inverted half pyramid pattern as shown in the image above, we will use an outer loop where we will use the decrement operator to create an inverted pattern. For the inner loop, we will use the increment operator to print * as many as i times.
Let’s look at 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=1; j<=i; j++){cout << " * " ;}cout << endl ;}return 0;}
Enter the input below
Explanation
Please enter a number above to generate an output.
-
In line 5, we initialize a variable
number. -
In line 6, we take the input as
number. -
In line 7, we initialize an outer
forloop, where we give a condition to run the loop until the value ofiis greater than or equal to1. We use the decrement operator so that it can print*in an inverted form. -
In line 9, we initialize an inner
forloop, where we have given conditions to run the loop foritimes. -
In line 11, we have given a condition to print
*. It will print foritimes as given in the condition in the code. -
In line 13, we print a next line character. This is done so that the star gets printed now from the next line onwards.
In this way, we can make an inverted half pyramid pattern with loops in C++.
This pattern can also be made with numbers, alphabets, or any other characters.