Learn-c-by-examples-upside-down-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 from 1 to I
Step 5 - Return

疑似コード

次のように、上記のアルゴリズムの擬似コードを導出できます-

procedure upsidedown_triangle

   FOR I = 1 to N DO
      FOR J = 1 to N-I 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;

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

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

      printf("\n");
   }

   return 1;
}

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

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