Learn-c-by-examples-floyds-triangle-program-in-c
提供:Dev Guides
Cのフロイドの三角形プログラム
Rober Floydにちなんで名付けられたフロイドの三角形は、自然数を使って作られた直角三角形です。 1から始まり、次に大きい番号を順番に選択します。
ここでは、Cプログラミング言語を使用してフロイドの三角形を印刷する方法を学習します。
アルゴリズム
アルゴリズムは次のようになります-
Step 1 - Take number of rows to be printed, n.
Step 2 - Make outer iteration I for n times to print rows
Step 3 - Make inner iteration for J to I
Step 3 - Print K
Step 4 - Increment K
Step 5 - Print NEWLINE character after each inner iteration
Step 6 - Return
疑似コード
次のように、上記のアルゴリズムの擬似コードを導出できます-
procedure floyds_triangle
FOR I = 1 to N DO
FOR J = 1 to I DO
PRINT K
INCREMENT K
END FOR
PRINT NEWLINE
END FOR
end procedure
実装
Cでの直角三角形の実装は次のとおりです-
#include <stdio.h>
int main() {
int n,i,j,k = 1;
n = 5;
for(i = 1; i <= n; i++) {
for(j = 1;j <= i; j++)
printf("%3d", k++);
printf("\n");
}
return 0;
}
出力は次のようになります-
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15