How to make diamond shape pattern in C++

In this tutorial, we will learn how to make a diamond shape pattern by asterisks sign in the C++ language. In this task, we will get a number n and we have to print the diamond shape of 2*n rows.
For Example:

Input: 5
Output: 
           *
          ***
         *****
        ******* 
       *********
       *********
        *******
         *****
          ***
           *

C++ program to make diamond shape pattern

#include<iostream>
using namespace std;

void printDiamond( int n ){
    int i,j,s;

    for(i=1;i<=n;i++){
        for(s=1;s<=n-i;s++)
             cout<<" ";

        for(j=1;j<=i*2-1;j++)
             cout<<"*";

        cout<<endl;
    }

    for(i=n;i>=1;i--){

         for(s=1;s<=n-i;s++)
            cout<<" ";

        for(j=1;j<=i*2-1;j++)
            cout<<"*";

        cout<<endl;
    }
  }

int main()
{

    printDiamond( 5 );

    return 0;
  }

Output:

    *
   ***
  *****
 *******
*********
*********
 *******
  *****
   ***
    *

Time complexity: O(n^2)

Explanation

In the main function, there is three variable of integer type i, j, and s. These variables are for loops to print “*” and spaces (” “). The for loop driven by i is for the row, loop driven by j is for the column to print “*” and the loop driven by s is for the column to print space (” “).

The logic of the above program is simple. you can see the diamond shape in the output is made by two triangles. one, from the 1st row to nth two and second is inverted from the base, i.e. from (n+1)th row to 2*n.

line 7 – 15: The nested loop in the line is to print the first triangle i.e. from 1st row to nth row. The loop, driven by i for the rows of the first triangle. Therefore, the outer loop will run from 1 to n. Inside the outer loop, there are two inner loops. First is to print spaces and second is to print the asterisks. The first inner loop will run from 1 to n – 1 because with each row the number of asterisks (“*”) is increasing and hence we need to decrease the space in each column of each preceding row. After printing the spaces the second inner loop will run from 1 to 2*i-1, this is because on each row we are printing odd numbers of “*” and with each row, the number of “*”  is also increasing. After printing asterisks in each row, the line will change in the output screen.

line 17 – 26: The nested loop in the line is to print the second inverted triangle. All the logic to print the inverted triangle is the same as above instead of conditions of loops. The outer loop will start for n to 1 as we need n-1 asterisks at first row of the second triangle and one asterisk at the last row i.e. nth row of the second triangle. And the two inner loops is the same as explained in line 7 – 15

Leave a Reply

Your email address will not be published. Required fields are marked *