Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
communitycreator

How to generate a full pyramid pattern in C++ using numbers

Vinisha Maheshwari

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

Approach

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

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

Full Pyramid Pattern

We will use a for loop and a while loop to generate this full pyramid pattern. In these loops, we will give conditions to print spaces and numbers in each row.

Code

Take a look at the code snippet below to understand this better.

#include <iostream>
using namespace std;

int main() {
  int row, counter = 0, counter1 = 0, h;
  cin >> row;
  for (int i = 1; i <= row; i++)
  {
    for (int j = 1; j <= row - i; j++)
    {
      cout << "  ";
      ++counter;
    }
    while (h != 2 * i - 1)
    {
      if (counter <= row-1){
        cout << i + h << " ";
        ++counter;
      } 
      else {
        ++counter1;
        cout << i + h - 2 * counter1 << " ";
      }
      ++h;
    }
    counter1 = counter = h = 0;
    cout << endl;
  } 
  return 0;
}

Enter the input below

Solid Full Pyramid Pattern in C++ using numbers

Please enter a number above to generate an output.

Explanation

  • In line 5, we initialize the variables row, counter, counter1, and h.

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

  • In line 7, we initialize an outer for loop, where we give a condition to run the loop for row times.

  • In line 9, we initialize an inner for loop, where we give a condition to run the loop for row - i times to print space.

  • From lines 14 to 25, we initialize the while loop, where we give if-else conditions to print number in each row.

  • In line 27, we print a next line character. We do this so that the number gets printed from the next line onwards.

RELATED TAGS

c++
communitycreator
RELATED COURSES

View all Courses

Keep Exploring