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.
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.
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.
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 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
In this lab, we learned how to print a reverse half pyramid structure with numbers using nested loops in the C++ programming language.