Introduction
In this lab, we will learn how to print a reverse half pyramid pattern in C++. We will be using two different methods for this, one using asterisks (*) and the other using numbers.
In this lab, we will learn how to print a reverse half pyramid pattern in C++. We will be using two different methods for this, one using asterisks (*) and the other using numbers.
First, we need to create a new C++ file in the ~/project
directory. We can name it main.cpp
. To create a new file, open the terminal and enter the following command:
cd ~/project
touch main.cpp
In this step, we will write a C++ program to print the reverse half pyramid pattern using asterisks (*). To do this, we need to use nested for loops. The outer loop will be used to iterate through the rows, and the inner loop will be used to print the asterisks on each row.
#include <iostream>
using namespace std;
int main() {
int rows;
cout << "Enter number of rows: ";
cin >> rows;
for(int i = rows; i >= 1; --i) {
for(int j = 1; j <= i; ++j) {
cout << "* ";
}
cout << "\n";
}
return 0;
}
To run this program, we need to compile and execute it. To do this, we need to enter the following command in the terminal:
g++ main.cpp -o main && ./main
This will compile the program and execute it, and the output will be displayed on the terminal.
In this step, we will write a C++ program to print the reverse half pyramid pattern using numbers. To do this, we need to replace the asterisks with numbers in the inner loop of the previous program.
#include <iostream>
using namespace std;
int main() {
int rows;
cout << "Enter number of rows: ";
cin >> rows;
for(int i = rows; i >= 1; --i) {
for(int j = 1; j <= i; ++j) {
cout << j << " ";
}
cout << "\n";
}
return 0;
}
To run this program, we need to compile and execute it. To do this, we need to enter the following command in the terminal:
g++ main.cpp -o main && ./main
This will compile the program and execute it, and the output will be displayed on the terminal.
After completing the above steps, our main.cpp
file will contain the following code:
#include <iostream>
using namespace std;
int main() {
int rows;
// Printing the Reverse Half Pyramid Using Asterisks (*)
cout << "Enter number of rows: ";
cin >> rows;
for(int i = rows; i >= 1; --i) {
for(int j = 1; j <= i; ++j) {
cout << "* ";
}
cout << "\n";
}
// Printing the Reverse Half Pyramid Using Numbers
cout << "Enter number of rows: ";
cin >> rows;
for(int i = rows; i >= 1; --i) {
for(int j = 1; j <= i; ++j) {
cout << j << " ";
}
cout << "\n";
}
return 0;
}
In this lab, we learned how to print the reverse half pyramid pattern in C++ using two different methods - using asterisks (*) and using numbers. We used nested for loops to achieve this pattern. We also learned how to compile and execute a C++ program in the terminal.