Learn-c-by-examples-equilateral-triangle-printing-in-c

提供:Dev Guides
移動先:案内検索

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;
}

出力は次のようになります-

    *
    * *
   * * *
  * * * *
 * * * * *