Open In App

C Program To Print Diamond Pattern

Here, we will see how to print a full diamond shape pyramid using the C program. Below are the examples:

Input: 6
Output:



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

Input: 8
Output:



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

Approach:

1. The first step is to print the upper part of the diamond using three nested loops. 

  1. The first loop handles the number of rows.
  2. The Second loop is for the initial space before the stars.
  3. The third loop print the stars. 

2. Now Repeat again steps 1, 2, and 3 in reverse order to print the lower part of the diamond.

Below is the C program to print full diamond shape pyramid:




// C program to print full
// diamond shape pyramid
#include <stdio.h>
  
// Prints diamond pattern
void printDiamond(int n)
{
    int space = n - 1;
  
    // Run loop till the number 
    // of rows
    for (int i = 0; i < n; i++)
    {
        // Loop for the initially space 
        // before the star printing
        for (int j = 0; j < space; j++)
            printf(" ");
  
        // Print the i+1 stars
        for (int j = 0; j <= i; j++)
            printf("* ");
  
        printf("\n");
        space--;
    }
  
    // Repeat again in the reverse order
    space = 0;
  
    // run a loop till number of rows
    for (int i = n; i > 0; i--) 
    {
        // Loop for the initially space 
        // before the star printing
        for (int j = 0; j < space; j++)
            printf(" ");
  
        // Print the i stars
        for (int j = 0; j < i; j++)
            printf("* ");
  
        printf("\n");
        space++;
    }
}
  
// Driver code
int main()
{
    printDiamond(8);
    return 0;
}

Output
       * 
      * * 
     * * * 
    * * * * 
   * * * * * 
  * * * * * * 
 * * * * * * * 
* * * * * * * * 
* * * * * * * * 
 * * * * * * * 
  * * * * * * 
   * * * * * 
    * * * * 
     * * * 
      * * 
       * 

Time Complexity: O(n*n) since here we are traversing the rows and columns of a grid for printing spaces ‘ ‘ and star ‘*’.

Auxiliary Space: O(1), No extra Space is used.


Article Tags :