在这里,为了以菱形图案打印星星,我们使用嵌套的 for 循环。
我们用于以菱形图案打印星星的逻辑如下所示 -
//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("
");}
假设让我们考虑 rows=5,它打印输出如下 -
* *** ***** ******* *********
//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("
");}
假设 row=5,将打印以下输出 -
******* ***** *** *
示例#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;}
输出enter no of rows5 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
以上就是如何使用c语言打印出菱形图案中的星星?的详细内容。