Home > Backend Development > C++ > body text

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

PHPz
Release: 2023-09-03 14:41:06
forward
1402 people have browsed it

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>");
}
Copy after login

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

      *
     ***
    *****
   *******
  *********
Copy after login

//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>");
}
Copy after login

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

*******
  *****
  ***
   *
Copy after login

Example