Trusted answers to developer questions

Generate an inverted half pyramid pattern with stars in C++

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

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 for loop, where we give a condition to run the loop until the value of i is greater than or equal to 1. We use the decrement operator so that it can print * in an inverted form.

  • In line 9, we initialize an inner for loop, where we have given conditions to run the loop for i times.

  • In line 11, we have given a condition to print *. It will print for i times 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.

RELATED TAGS

c++
loop
Did you find this helpful?