Introduction
In this lab, you will learn how to write a C++ program to print a full pyramid using *. The program will prompt the user to enter the number of rows they want to print and then it will print a full pyramid with that many rows.
In this lab, you will learn how to write a C++ program to print a full pyramid using *. The program will prompt the user to enter the number of rows they want to print and then it will print a full pyramid with that many rows.
In this step, you need to include the necessary header files.
#include<iostream>
using namespace std;
In this step, you will create the main function which is the entry point of the program.
int main()
{
int space, rows;
cout <<"Enter number of rows: ";
cin >> rows;
for(int i = 1, k = 0; i <= rows; ++i, k = 0)
{
for(space = 1; space <= rows-i; ++space)
{
cout <<" ";
}
while(k != 2*i-1)
{
cout << "* ";
++k;
}
cout << endl;
}
return 0;
}
To test the program, run the following command in the terminal.
g++ main.cpp -o main && ./main
You will see the following output:
Enter number of rows: 5
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
Here is the full code for main.cpp
.
#include<iostream>
using namespace std;
int main()
{
int space, rows;
cout <<"Enter number of rows: ";
cin >> rows;
for(int i = 1, k = 0; i <= rows; ++i, k = 0)
{
for(space = 1; space <= rows-i; ++space)
{
cout <<" ";
}
while(k != 2*i-1)
{
cout << "* ";
++k;
}
cout << endl;
}
return 0;
}
In this lab, you have learned how to write a C++ program to print a full pyramid using *, by prompting the user to enter the number of rows they want to print and then printing a full pyramid with that many rows. Now you can practice using this program to create similar patterns for your own projects.