Introduction
In this lab, you will learn how to print a half pyramid structure using characters, in the C++ programming language. We will guide you through the entire process of developing this program.
In this lab, you will learn how to print a half pyramid structure using characters, in the C++ programming language. We will guide you through the entire process of developing this program.
First, we need to create a C++ program file. Open your terminal and go to the ~/project
directory. Create a new file named main.cpp
by executing the following command:
touch main.cpp
In this step, we will include the necessary header files and namespaces required for this program. Open the main.cpp
file and type in the following code:
#include <iostream>
using namespace std;
The first line includes the iostream
header file, which provides the ability to perform standard input and output operations in C++ programs. The second line includes the std
namespace, which is used to avoid writing the std::
prefix before any standard library function.
In this step, we will define the main function. The main function is the entry point for a C++ program and is where the actual execution of the program takes place. Type the following code into main.cpp
:
int main()
{
//TODO: Add code here
return 0;
}
In this step, we will declare variables and accept user input. We need to declare two variables to iterate through the rows and columns of the pyramid. The user will input the number of rows to be printed. Type the following code into main.cpp
:
int i, j, rows;
cout << "Enter the number of rows in the pyramid: ";
cin >> rows;
In this step, we will print the pyramid pattern. We will use nested loops to print the rows and columns of the pyramid. Type the following code into main.cpp
:
char c = 'A';
for(i=1; i<=rows; i++)
{
cout<<"Row ## " <<i<<" ";
c = 'A';
for(j=1; j<=i; j++)
{
cout<<c<<" ";
c++;
}
cout<<endl;
}
In this step, we will compile and run the program to see the output. Open your terminal and execute the following commands:
g++ main.cpp -o main
./main
You will see the following output:
Enter the number of rows in the pyramid: 5
Row ## 1 A
Row ## 2 A B
Row ## 3 A B C
Row ## 4 A B C D
Row ## 5 A B C D E
Congratulations on completing this lab! In this lab, you have learned how to print a half pyramid structure using characters in the C++ programming language. We covered important concepts like nested loops and user input. Keep practicing by modifying the program and exploring more advanced concepts in C++.