Here, we will build a C++ program to print the hollow star pyramid diamond shape pattern that can be achieved with two approaches i.e.
- Using for Loop
- Using while loop
Input:
n = 5
Output:
*
* *
* *
* *
* *
* *
* *
* *
*1. Using for loop
// C++ program to print hollow diamond pattern
#include <iostream>
using namespace std;
int main()
{
int n = 5, rows, columns;
// for loop is used to identify the number of rows and
// it is used to print upper triangle
for (rows = 1; rows <= n; rows++) {
// used for printing the spaces
for (columns = n; columns > rows; columns--) {
cout << " ";
}
// print star
cout << "*";
// again print the spaces
for (columns = 1; columns < (rows - 1) * 2;
columns++) {
cout << " ";
}
if (rows == 1) {
cout << "\n";
}
else {
cout << "*\n";
}
}
// for loop is used to identify the number of rows and
// it is used to print lower triangle
for (rows = n - 1; rows >= 1; rows--) {
// used for printing the spaces
for (columns = n; columns > rows; columns--) {
cout << " ";
}
// print star
cout << "*";
for (columns = 1; columns < (rows - 1) * 2;
columns++) {
cout << " ";
}
if (rows == 1) {
cout << "\n";
}
else {
cout << "*\n";
}
}
return 0;
}
Output
*
* *
* *
* *
* *
* *
* *
* *
*Time complexity: O(n2) for given input n
Auxiliary Space: O(1)
2. Using while loop:
// C++ program to print hollow diamond pattern
#include <iostream>
using namespace std;
int main()
{
int n = 5, rows = 1, columns;
// while loop is used to identify the number of rows and
// it is used to print upper triangle
while (rows <= n) {
columns = n;
// used for printing the spaces
while (columns > rows) {
cout << " ";
columns--;
}
// print star
cout << "*";
columns = 1;
while (columns < (rows - 1) * 2) {
cout << " ";
columns++;
}
if (rows == 1) {
cout << "\n";
}
else {
cout << "*\n";
}
rows++;
}
// while loop is used to identify the number of rows and
// it is used to print lower triangle
rows = n - 1;
while (rows >= 1) {
columns = n;
// used for printing the spaces
while (columns > rows) {
cout << " ";
columns--;
}
// print star
cout << "*";
columns = 1;
while (columns < (rows - 1) * 2) {
cout << " ";
columns++;
}
if (rows == 1) {
cout << "\n";
}
else {
cout << "*\n";
}
rows--;
}
return 0;
}
Output
*
* *
* *
* *
* *
* *
* *
* *
*Time complexity: O(rows*columns)
Auxiliary Space: O(1)