Introduction
In this lab, you will learn how to create a half pyramid pattern using stars (*) by using the C++ programming language. This lab will teach you how to implement various nested loop structures using iteration.
In this lab, you will learn how to create a half pyramid pattern using stars (*) by using the C++ programming language. This lab will teach you how to implement various nested loop structures using iteration.
~/project
directoryFirst, create a new file called half_pyramid_star.cpp
in the ~/project
directory using the touch command in the terminal:
touch ~/project/half_pyramid_star.cpp
Now, open the half_pyramid_star.cpp
file in a text editor or IDE, and copy the following code into it:
#include <iostream>
using namespace std;
int main()
{
cout << "\n\nWelcome to Studytonight :-)\n\n\n";
cout << "===== Program to print a Half Pyramid using * =====\n\n\n";
int i, j, rows;
cout << "Enter the number of rows in the pyramid: ";
cin >> rows;
//outer loop moves to a specific row
for (i = 1; i <= rows; i++)
{
//inner loop determines the amount of "*" printed in the row
for (j = 1; j <= i; j++)
{
cout << "* ";
}
cout << endl;
}
cout << "\n\n";
return 0;
}
The code above prompts the user to enter the number of rows to print the half pyramid pattern and uses two nested loops to print "*" on each line.
Enter the following command in the terminal window to compile the half_pyramid_star.cpp
code:
g++ ~/project/half_pyramid_star.cpp -o ~/project/half_pyramid_star && ~/project/half_pyramid_star
The above command will compile the code, create an executable file called half_pyramid_star
, and run the program.
In this lab, you learned how to create a half pyramid pattern using stars (*) in C++ programming language. By utilizing nested loops and understanding their scope, you were able to complete the lab successfully. This lab is a fundamental step in building an understanding of nested loop structures and iteration, which will be helpful in solving problems or creating complex shapes.