Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
communitycreator

How to generate a hollow half pyramid pattern with stars in C++

Vinisha Maheshwari

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++.

Approach

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.

Hollow half pyramid pattern

In this hollow half pyramid pattern, the * will print on the edges of the pyramid and it will be hollow inside.

Code

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 << " * ";
       else
       cout << "   ";
     }
     cout << endl;
   }
  return 0;
}

Enter the input below

Generate a hollow half pyramid pattern with stars in C++

(Please enter a number in the input section.)

Explanation

  • 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.

RELATED TAGS

c++
communitycreator
RELATED COURSES

View all Courses

Keep Exploring