C++ Reverse Half Pyramid Pattern Using Numbers

Beginner

Introduction

In this lab, we will learn how to print a Reverse Half Pyramid Structure using Numbers, in the C++ programming language. We will use the nested loop structures to iterate and print the pattern.

Create and Open the File

Go to the terminal and create a new file named main.cpp in the ~/project directory using the following command:

touch ~/project/main.cpp

After creating the file, open it using a text editor.

Write the Initial Code

Add the following code to the main.cpp file.

#include <iostream>
using namespace std;

int main()
{
    cout << "\n\nWelcome to Studytonight :-)\n\n\n";
    cout << " =====  Program to print a Reverse Half Pyramid using Numbers ===== \n\n";

    //i to iterate the outer loop and j for the inner loop
    int i, j, rows;

    //to denote the range of numbers in each row
    int last;

    cout << "Enter the number of rows in the pyramid: ";
    cin >> rows;
    cout << "\n\nThe required Reverse Pyramid pattern containing " << rows << " rows is:\n\n";

    //outer loop is used to move to a particular row
    for (i = 1; i <= rows; i++)
    {
        //to display that the outer loop maintains the row number
        cout << "Row ## " << i << " contains numbers from 1 to " << (rows - i + 1) << " :  ";

        last  = rows -i + 1;
        //inner loop is used to decide the number of * in a particular row
        for (j = 1; j<= last; j++)
        {
            cout << j << " ";
        }

        cout << endl;
    }

    cout << "\n\n";

    return 0;
}

Compile and Run the Code

Compile and run the code using the following commands:

g++ main.cpp -o main
./main

You will see the following output:

Welcome to Studytonight :-)


 =====  Program to print a Reverse Half Pyramid using Numbers =====

Enter the number of rows in the pyramid: 6


The required Reverse Pyramid pattern containing 6 rows is:

Row ## 1 contains numbers from 1 to 6 :  1 2 3 4 5 6
Row ## 2 contains numbers from 1 to 5 :  1 2 3 4 5
Row ## 3 contains numbers from 1 to 4 :  1 2 3 4
Row ## 4 contains numbers from 1 to 3 :  1 2 3
Row ## 5 contains numbers from 1 to 2 :  1 2
Row ## 6 contains numbers from 1 to 1 :  1

Summary

In this lab, we learned how to print a reverse half pyramid structure with numbers using nested loops in the C++ programming language.

Other Tutorials you may like