如何使用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
            *
          * * *
        * * * * *
      * * * * * * *
    * * * * * * * * *
      * * * * * * *
        * * * * *
         * * *
           *

更新於: 05-03-2021

605次觀看

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.