Learn-c-by-examples-top-down-triangle-printing-in-c
提供:Dev Guides
Cのトップダウン三角形印刷
角度が90°の三角形は、直角三角形と呼ばれます。 ここで、星*を直角三角形の形で、ただしy軸を逆さまにして印刷する方法を確認します。
アルゴリズム
アルゴリズムは次のようになります-
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 "*" (star)
Step 4 - Print NEWLINE character after each inner iteration
Step 5 - Return
疑似コード
次のように、上記のアルゴリズムの擬似コードを導出できます-
procedure topdown_triangle
FOR I = 1 to N 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 = 0; i < n; i++) {
for(j = 0; j<i; j++)
printf(" ");
for(j = i; j < n; j++)
printf(" *");
printf("\n");
}
return 0;
}
出力は次のようになります-
* * * * *
* * * *
* * *
* *
*