如何使用C語言列印菱形圖案的星星?
在這裡,為了按菱形圖案列印星星,我們使用巢狀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("
");
}假設我們考慮行數=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("
");
}假設行數=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 rows 5 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP