C++ Program To Print Hollow Star Pyramid Diamond Shape Pattern
Last Updated :
10 Aug, 2022
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++
#include <iostream>
using namespace std;
int main()
{
int n = 5, rows, columns;
for (rows = 1; rows <= n; rows++) {
for (columns = n; columns > rows; columns--) {
cout << " " ;
}
cout << "*" ;
for (columns = 1; columns < (rows - 1) * 2;
columns++) {
cout << " " ;
}
if (rows == 1) {
cout << "\n" ;
}
else {
cout << "*\n" ;
}
}
for (rows = n - 1; rows >= 1; rows--) {
for (columns = n; columns > rows; columns--) {
cout << " " ;
}
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++
#include <iostream>
using namespace std;
int main()
{
int n = 5, rows = 1, columns;
while (rows <= n) {
columns = n;
while (columns > rows) {
cout << " " ;
columns--;
}
cout << "*" ;
columns = 1;
while (columns < (rows - 1) * 2) {
cout << " " ;
columns++;
}
if (rows == 1) {
cout << "\n" ;
}
else {
cout << "*\n" ;
}
rows++;
}
rows = n - 1;
while (rows >= 1) {
columns = n;
while (columns > rows) {
cout << " " ;
columns--;
}
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)
Share your thoughts in the comments
Please Login to comment...