A hollow diamond pattern is a star pattern in which only the boundary of the diamond is printed, while the inside is filled with spaces. The pattern is formed by combining an upper and a lower hollow pyramid.
- The number of rows in the complete diamond is 2n - 1.
- Nested loops are used to control leading spaces and the hollow space between the boundary stars.
Illustration
For n = 5, the pattern contains 2n - 1 = 9 rows:
*
* *
* *
* *
* *
* *
* *
* *
*
Using for Loop
The upper half is printed first, followed by the lower half. For each row, the program prints leading spaces, a boundary star, the required inner spaces, and another boundary star.
#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
*
* *
* *
* *
* *
* *
* *
* *
*Using while Loop
The same pattern can be generated using while loops. The first part prints the upper half, and the second part prints the lower half.
#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
*
* *
* *
* *
* *
* *
* *
* *
*