C 語言等邊三角形列印



三條邊都相等的三角形稱為等邊三角形。現在我們來看看怎樣打印出以等邊三角形形狀排列的星號 *。

演算法

演算法應該像這樣 −

Step 1 - Take number of rows to be printed, n.
Step 2 - Make an iteration for n times
Step 3 - Print " " (space) for in decreasing order from 1 to n-1
Step 4 - Print "* " (start, space) in increasing order
Step 5 - Return

虛擬碼

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

procedure equi_triangle

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

實現

C 語言中實現等邊三角形的程式碼如下 −

#include <stdio.h>

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

   n = 5;   // number of rows.

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

      for(j = 1; j <= i; j++)
         printf("* ");

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

輸出應該像這樣 −

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