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("\n");
}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("\n");
}Suppose row=5, the following output will be printed −
******* ***** *** *
Example
#include <stdio.h>
int main(){
int rows, i, j;
printf("Enter no of rows\n");
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("\n");
}
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("\n");
}
return 0;
}Output
Enter no of rows 5 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *