Hollow Diamond Inscribed in a Rectangle Pattern in C++
In this article, we are going to learn how to print a Hollow Diamond Inscribed in a Rectangle Pattern using C++. This pattern is possible and easy to understand in C++.
let us understand first what is Hollow Diamond and how it is inscribed in a Rectangle?
We will print this pattern by using asterisks/stars (*). The size of the pattern will be dependent on the user in how many rows he/she wants in this particular pattern. In this pattern, a rectangle of any size will be there having a diamond-shaped vacant space in between. For example:
The above Pattern is containing 5 rows which will be entered by the user.
C++ Program to print pattern of hollow diamond inscribed in a rectangle
We can print this pattern by using “for loops and Nested for loops”. Firstly, we will print stars in decreasing order to obtain the required shape of the rectangle around the diamond. We will write codes of spaces and stars only for half of the pattern as the lower part of the pattern is a mirror image of the upper part. So, if we reverse the first loop then we will get the same shape as of upper one. Let us understand this by source code:
#include<iostream> using namespace std; int main() { int i,j,k,r; cout<<"Enter no. of rows: "; cin>>r; for(i=1;i<=r;i++) { for(j=1;j<=r-i;j++) cout<<"*"; for(k=1;k<=2*i-1;k++) { if(k==1 || k==2*i-1) cout<<"*"; else cout<<" "; } for(j=1;j<=r-i;j++) cout<<"*"; cout<<"\n"; } for(i=r;i>=1;i--) { for(j=1;j<=r-i;j++) cout<<"*"; for(k=1;k<=2*i-1;k++) { if(k==1 || k==2*i-1) cout<<"*"; else cout<<" "; } for(j=1;j<=r-i;j++) cout<<"*"; cout<<"\n"; } return 0; }
In the above code i, j, k are the integer variables that will control the loops and r is the number of rows entered by the user.
i-loop will control rows of this pattern whereas j-loop and k-loop will print spaces and stars respectively. We will need to apply some logic in the printing of those stars and spaces which are already given in codes. By tracing them, you can easily get your hands on them. It is written in a very minimal and easy way which makes it fun to learn.
Now, let us see an example in the output screen after executing it:
Enter no. of rows: 10
In this way, you can print a Hollow Diamond by using C++ language. I hope it was easy enough to understand. If you have any doubt, feel free to ask in the comment section. All the best!
You may also learn:
Hollow Diamond Pattern Program in C++
Thank you!
Regards,
Isha Rani Prasad
It is very easy to understand and your explanation way is very easy and very helpful. Thnq… Please update more pattern.