In this post, we will understand of the C++ Program to print diamond patterns. We can draw a diamond shape using nested loop. To understand it better we must have knowledge of nested loop in C++.
C++ Program to print diamond pattern of start
In this code, we are asking the user to enter a number to draw a diamond shape. As per user need it to draw a diamond pattern dynamically in c++.
#include<iostream>
using namespace std;
main()
{
int num, i, j, space=1;
cout<<"Please enter the no to print diamond shape : ";
cin>>num;
space=num-1;
for (i=1; i<=num; i++) { //outer loop
for(j=1; j<=space; j++) //ineer loop
{
cout<<" "; //printing space.
}
space--;
for(j=1; j<=(2*i-1); j++)
{
cout<<"*"; //print stars.
}
cout<<"\n"; //for new line
}
//printing in reverse order.
space=1;
for (i=1; i<=num; i++) {
for(j=1; j<=space; j++) {
cout<<" "; //printing space.
}
space++;
for(j=1; j<=(2*(num-i)-1); j++) {
cout<<"*"; //printing stars.
}
cout<<"\n"; //new line
}
}
Output
Please enter the no for for print diamond : 4
*
***
*****
*******
*****
***
*
C++ Program to print diamond pattern of &
We can change the diamond shape pattern using start to any special character as per our requirement. Let understand with example in the below example we are using and special operator to draw a diamond shape pattern
#include<iostream>
using namespace std;
main()
{
int num, i, j, space=1;
cout<<"Please enter the no for for print diamond : ";
cin>>num;
space=num-1;
for (i=1; i<=num; i++) { //outer loop
for(j=1; j<=space; j++) //ineer loop
{
cout<<" "; //printing space.
}
space--;
for(j=1; j<=(2*i-1); j++)
{
cout<<"&"; //print stars.
}
cout<<"\n"; //for new line
}
//printing in reverse order.
space=1;
for (i=1; i<=num; i++) {
for(j=1; j<=space; j++) {
cout<<" "; //printing space.
}
space++;
for(j=1; j<=(2*(num-i)-1); j++) {
cout<<"&"; //printing stars.
}cc
cout<<"\n"; //new line
}
}
Output
Please enter the no for for print diamond : 5
&
&&&
&&&&&
&&&&&&&
&&&&&&&&&
&&&&&&&
&&&&&
&&&
&