How to print the stars in Diamond pattern using C language?


Here, to print stars in diamond pattern, we are using nested for loops.

The logic that we use to print stars in diamond pattern is shown below −

//For upper half of the diamond the logic is:
for (j = 1; j <= rows; j++){
   for (i = 1; i <= rows-j; i++)
      printf(" ");
   for (i = 1; i<= 2*j-1; i++)
      printf("*");
   printf("
"); }

Suppose let us consider rows=5, it prints the output as follows −

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


//For lower half of the diamond the logic is:
for (j = 1; j <= rows - 1; j++){
   for (i = 1; i <= j; i++)
      printf(" ");
   for (i = 1 ; i <= 2*(rows-j)-1; i++)
      printf("*");
   printf("
"); }

Suppose row=5, the following output will be printed −

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

Example

#include <stdio.h>
int main(){
   int rows, i, j;
   printf("Enter no of rows
");    scanf("%d", &rows);    for (j = 1; j <= rows; j++){       for (i = 1; i <= rows-j; i++)          printf(" ");       for (i = 1; i<= 2*j-1; i++)          printf("*");       printf("
");    }    for (j = 1; j <= rows - 1; j++){       for (i = 1; i <= j; i++)          printf(" ");       for (i = 1 ; i <= 2*(rows-j)-1; i++)          printf("*");       printf("
");    }    return 0; }

Output

Enter no of rows
5
            *
          * * *
        * * * * *
      * * * * * * *
    * * * * * * * * *
      * * * * * * *
        * * * * *
         * * *
           *

Updated on: 05-Mar-2021

524 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements