How to generate a hollow diamond pattern with stars in C++

In this shot, we will discuss how to make a hollow diamond pattern in C++ with stars.

Approach

We will use the nested loop to generate this pattern. A nested loop means there is an outer loop inside which there is another loop called an inner loop.

Let’s look at the below image to understand this better.

Hollow Full Diamond Pattern

We will generate a hollow full diamond pattern as shown in the image above. We will use the for loop and the while loop to generate the upper half and the bottom half of the diamond.

Code

Let’s look at the code snippet below to understand this better.

#include <iostream>
using namespace std;
int main() {
int number, i, j, k=0;
cin>> number;
// upper half of diamond
for (i = 1; i <= number; i++)
{
for (j = 1; j <= number-i; j++)
{
cout << " " ;
}
while (k != (2*i-1))
{
if (k == 0 || k == 2*i-2)
cout << "*" ;
else
cout << " " ;
k++;
}
k = 0;
cout << endl;
}
// lower half of diamond
number--;
for (i = number; i >= 1; i--)
{
for (j = 0; j <= number-i; j++)
{
cout << " " ;
}
k=0;
while (k != (2*i-1))
{
if (k == 0 || k == 2*i-2)
cout << "*";
else
cout << " ";
k++;
}
cout << endl;
}
return 0;
}

Enter the input below

Please enter a number above to generate output.

Explanation

  • In line 5, we initialize the number, i, j, and k variables.

  • In line 6, we take the input as number.

  • From lines 8 to 24, we initialize a for loop and a while loop where we have given conditions so as to print * and ( ) to generate the upper half of the diamond.

  • From lines 27 to 43, we initialize another for loop and while loop where we have given conditions so as to print * and ( ) to generate the bottom half of the diamond. We use the decrement operator so that * gets printed in decreasing order.

In this way, we have learned to generate a hollow full diamond pattern with stars in C++.

We can also use numbers, alphabets, or any other characters to generate this pattern.

Free Resources