Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
loop
nested
communitycreator

How to generate a hollow full pyramid pattern with numbers in C++

Vinisha Maheshwari

In this shot, we will discuss how to make a hollow full pyramid pattern with numbers in C++.

Approach

We will use a nested loop to make the hollow full pyramid pattern in C++. A nested loop means a loop inside another loop.

Let’s look at an image of the pattern that we will generate.

Hollow Full Pyramid Pattern

We have used for loops to generate the hollow full pyramid pattern as shown in the image above. We have used an outer and three inner loops to print the left side, right side, and bottom of the hollow full pyramid pattern.

Let’s see the below code snippet to understand this better.

#include <iostream>
using namespace std;

int main() {
  int number, i, j;
  cin >> number;
  for (i = 1; i <= number; i++)
  {
    for (j = i; j < number; j++)
    {
      cout << " ";
    }
    for (j=1; j <= i; j++)
    {
      if (j==1 || i==number){
      cout << j << " ";
      } else {
      cout << " " ;
    }
    }
    for (j=1; j < number -1; j++)
    {
      if (j == i-1 && j < number-1) {
      cout << j+1;
      } else {
      cout << " " ;
      }
    }
    cout << endl;
  }
  return 0;
}

Enter the input below

Hollow Full Pyramid Pattern using numbers in C++

Please enter a number for the height of the pyramid in the input section.

Explanation

  • In line 5, we initialize the number, i, and j variables.

  • In line 6, we take the input as number.

  • In line 7, we initialize an outer for loop where we have given conditions to run the loop number times.

  • From lines 9 to 12, we initialize an inner loop where we give conditions to print the left side of the hollow full pyramid.

  • From lines 13 to 20, we initialize another inner for loop where we give conditions to print the right side of the hollow full pyramid.

  • From lines 21 to 28, we initialize another inner for loop where we give conditions to print the bottom side of the hollow full pyramid.

  • In line 29, we use a next line character so as to print the numbers from the next line onwards.

In this way, we have learned how to generate a hollow full pyramid pattern with numbers in C++.

RELATED TAGS

c++
loop
nested
communitycreator
RELATED COURSES

View all Courses

Keep Exploring