Introduction
In this lab, we will learn how to print a half pyramid pattern using the alternative of a star (*) and an alphabet. We will use the C++ programming language to write the code for this program. This lab is suitable for beginner-level programmers who want to practice their programming skills in C++.
Create a new C++ file
Create a new C++ file named main.cpp in the ~/project directory. This is where we will write the code for the program.
touch ~/project/main.cpp
Write the code
Copy and paste the following code into the main.cpp file. This code will print the half pyramid pattern using the alternative of a star and an alphabet.
#include <iostream>
using namespace std;
int main()
{
int i, j, n;
cout << "Enter the number of rows: ";
cin >> n;
for(i = 1; i <= n; i++)
{
for(j = 1; j <= i; j++)
{
if(j % 2 == 0)
cout << "A";
else
cout << "*";
}
cout << "\n";
}
return 0;
}
Compile and run the code
Open the terminal and navigate to the ~/project directory by using the cd project command. Then, use the following command to compile the main.cpp file:
g++ main.cpp -o main
This command will create an executable file named main. To run the program, use the following command:
./main
The program will ask you to enter the number of rows for the pattern. Enter the desired number and press Enter. The program will then print the half pyramid pattern using the alternative of a star and an alphabet.
Full code
Here is the full code for the main.cpp file:
#include <iostream>
using namespace std;
int main()
{
int i, j, n;
cout << "Enter the number of rows: ";
cin >> n;
for(i = 1; i <= n; i++)
{
for(j = 1; j <= i; j++)
{
if(j % 2 == 0)
cout << "A";
else
cout << "*";
}
cout << "\n";
}
return 0;
}
Summary
In this lab, we learned how to print the half pyramid pattern using the alternative of a star and an alphabet in C++. We used basic programming concepts like loops and conditional statements to generate the pattern. We then compiled and ran the program to test our code.



