In this program, you will learn in-depth about C++ program to print star pyramid patterns of various types using nested loops.
To print star pyramid patterns in C++ programming, we have used two nested for loops.
The outer for loop is responsible for the number of rows in star (*) pyramid triangle or patterns whereas inner for loop will print the required number of stars * in each row.
Let’s take a look at various star pattern printing programs in C++.
//C++ program to display full star pyramid
#include <iostream>
using namespace std;
int main()
{
int rows, i, j, space;
cout << "Enter number of rows: ";
cin >> rows;
for(i = 1; i <= rows; i++)
{
//for loop for displaying space
for(space = i; space < rows; space++)
{
cout << " ";
}
//for loop to display star equal to row number
for(j = 1; j <= (2 * i - 1); j++)
{
cout << "*";
}
cout << "\n";
}
return 0;
}
Output
//C++ program to display inverted full star pyramid
#include<iostream>
using namespace std;
int main()
{
int rows, i, j, space;
cout << "Enter number of rows: ";
cin >> rows;
for(i = rows; i >= 1; i--)
{
//for loop to put space
for(space = i; space < rows; space++)
cout << " ";
//for loop for displaying star
for(j = 1; j <= (2 * i - 1); j++)
cout << "* ";
cout << "\n";
}
return 0;
}
Output
//C++ program to display half star pyramid
#include <iostream>
using namespace std;
int main()
{
int n, i, j;
cout << "Enter number of rows: ";
cin >> n;
for(i = 1; i <= n; i++)
{
//print * equal to row number
for(j = 1; j <= i; j++)
{
cout << "* ";
}
cout << "\n";
}
return 0;
}
Output
//C++ program to display half inverted star pyramid
#include <iostream>
using namespace std;
int main()
{
int i, j, row;
cout << "Enter number of rows: ";
cin >> row;
for(i = row; i >= 1; i--)
{
//print * equal to row number
for(j = 1; j <= i; j++)
{
cout << "* ";
}
cout << "\n";
}
return 0;
}
Output
//C++ program to display hollow star pyramid
#include<iostream>
using namespace std;
int main()
{
int rows, i, j, space;
cout << "Enter number of rows: ";
cin >> rows;
for(i = 1; i <= rows; i++)
{
//for loop to put space in pyramid
for (space = i; space < rows; space++)
cout << " ";
//for loop to print star
for(j = 1; j <= (2 * rows - 1); j++)
{
if(i == rows || j == 1 || j == 2*i - 1)
cout << "*";
else
cout << " ";
}
cout << "\n";
}
return 0;
}
Output
//C++ program to display inverted hollow star pyramid
#include<iostream>
using namespace std;
int main()
{
int rows, i, j, space;
cout << "Enter number of rows: ";
cin >> rows;
for(i = rows; i >= 1; i--)
{
//for loop to put space in pyramid
for (space = i; space < rows; space++)
cout << " ";
//for loop to print star in pyramid
for(j = 1; j <= 2 * i - 1; j++)
{
if(i == rows || j == 1 || j == 2*i - 1)
cout << "*";
else
cout << " ";
}
cout << "\n";
}
return 0;
}
Output