Write a program to print Diamond pattern using C++
In this tutorial, we are going to learn how to write a program to print a diamond pattern in C++. The pattern can be of any size, it will depend on the number of rows entered by a user. The basic idea to print this pattern is to use for loop in the correct required manner.
At first, we have to print spaces then ‘*’ will be printed and this will be done till we reach the middle point and we start printing again in the reverse order. For example, if he enters 4 it will look like this:
* *** ***** ******* ***** *** *
Let us try to implement the above idea in our code:
C++ program to print Diamond pattern
The C++ Source code is given below:
// Program to print Diamond pattern #include<bits/stdc++.h> using namespace std; int main() { int row,space; cout<<"\nEnter the number of rows: "; cin>>row; space=row-1; for(int k=1;k<=row;k++) { for(int c=1;c<=space;c++) { cout<<" "; } space--; for(int c=1;c<=2*k-1;c++) { cout<<"*"; } cout<<"\n"; } space=1; for(int k=1;k<=row-1;k++) { for (int c=1;c<=space;c++) { cout<<" "; } space++; for (int c=1 ;c<=2*(row-k)-1;c++) { cout<<"*"; } cout<<"\n"; } return 0; }
Input/Output:
Below is how the output will be looks like:
Enter the number of rows: 6 * *** ***** ******* ********* *********** ********* ******* ***** *** *
You can also learn:
Do not forget to comment if you find anything wrong in the post or you want to share some information regarding the same.
Leave a Reply