Home  >  Article  >  Backend Development  >  How to print stars in a diamond pattern using C language?

How to print stars in a diamond pattern using C language?

PHPz
PHPzforward
2023-09-03 14:41:061400browse

How to print stars in a diamond pattern using C language?

Here, to print stars in a diamond pattern, we use nested for loops.

Our logic for printing stars in diamond pattern is as follows -

//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("</p><p>");
}

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("</p><p>");
}

Assuming row=5, the following output will be printed -

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

Example

The above is the detailed content of How to print stars in a diamond pattern using C language?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete