C program to print diamond star pattern

Write a C program to print the diamond star(*) pattern series using for loop. How to print diamond star pattern structure using for loop in C programming. The pattern should look like:
    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *

Required knowledge:

Basic C programming, For loop

Logic:

At single glance the patter seems difficult to be printed so, to make the pattern easy I have bisected the pattern in two halves. Where the first upper half looks like:
    *
   ***
  *****
 *******
*********
and the lower half looks like:
 *******
  *****
   ***
    *
And if you notice these two patters are simple pyramid (with n rows) and reverse pyramid pattern (with n-1 rows). Hence, we just need to write down the codes of both pyramid and reverse pyramid star pattern one by one to get the final pattern.

Program:

/**
 * C program to print diamond star pattern 
 */

#include <stdio.h>

int main()
{
    int i, j, n;

    printf("Enter value of n : ");
    scanf("%d", &n);
    
    //Prints the upper pyramid
    for(i=1; i<=n; i++)
    {
        for(j=i; j<n; j++)
        {
            printf(" ");
        }
        for(j=1; j<=(2*i-1); j++)
        {
            printf("*");
        }
        printf("\n");
    }

    //Prints the lower triangle
    for(i=n; i>=1; i--)
    {
        for(j=i; j<=n; j++)
        {
            printf(" ");
        }
        for(j=2; j<(2*i-1); j++)
        {
            printf("*");
        }
        printf("\n");
    }
    
    return 0;
} 


Output
X
_
Enter value of n : 5
    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *


Screenshot:

C program to print diamond star pattern

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment