用 C 語言列印倒置直角三角形



一個某個角度為 90° 的三角形稱為直角三角形。我們現在將介紹如何列印倒置在 x 軸上的右三角形的星號 *。

演算法

演算法應如下所示 -

Step 1 - Take number of rows to be printed, n.
Step 2 - Make outer iteration I from N to 1 times to print rows
Step 3 - Make inner iteration for J to I
Step 3 - Print "*" (star)
Step 4 - Print NEWLINE character after each inner iteration
Step 5 - Return

虛擬碼

我們可以為上述演算法匯出一個虛擬碼,如下 -

procedure topdownright_triangle

   FOR I = N to 1 DO
      FOR J = 1 to I DO
         PRINT "*" 
      END FOR
      PRINT NEWLINE
   END FOR
   
end procedure

實現

以下是 C 語言中直角三角形的實現 -

#include <stdio.h>

int main() {
   int n, i, j;

   n = 5;

   for(i = n; i >= 1; i--) {
      for(j = 1; j <= i; j++)
         printf("* ");

      printf("\n");
   }
   
   return 0;
}

輸出應如下所示 -

* * * * *
* * * *
* * *
* *
*
patterns_examples_in_c.htm
廣告
© . All rights reserved.