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.
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.
Please enter a number above to generate output.
Explanation
-
In line 5, we initialize the
number,i,j, andkvariables. -
In line 6, we take the input as
number. -
From lines 8 to 24, we initialize a
forloop and awhileloop 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
forloop andwhileloop 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.