[英]How does this code exactly work in C Language? (A Beginner Question)
此代碼用於打印倒半金字塔:
* * *
* *
*
#include<stdio.h>
int main() {
int i, j, rows;
printf("Enter number of rows: ");
scanf("%d", &rows);
for (i=rows; i>=1; --i)
{
for (j=1; j<=i; ++j)
{
printf("* ");
}
printf("\n");
}
return 0;
}
假設我輸入rows = 5,那么“i”將其值初始化為5,檢查它是否大於1,然后我們進入第二個for循環,其中j的初始值為1,然后檢查它是否大於1小於“i= 5”的值,它是,那么在那之后,第二個循環將如何運行?
第一個for
循環是從 5( rows
變量)減少到 1(因為它是倒半金字塔)。
第二個/內部for
循環(循環j
)是打印*
字符i
次( i
在外部for
循環中設置)。
一旦內部for
循環退出,將打印一個新行 ( \\n
) 並遞減i
並且內部循環再次運行以獲取i
的新值。
* * * *
* * *
* *
*
上面的模式包含N
行,每行包含Ni + 1
列(其中i
是當前行號)。 考慮到這一點,讓我們一步一步地編寫描述性邏輯來打印倒直角三角形星形圖案。
輸入要從用戶打印的行數。 將它存儲在一個變量中,比如rows
。
要遍歷行,請運行從 1 到rows
的外部循環。 循環結構應該類似於for(i=1; i<=rows; i++)
。
要遍歷列,請運行從i
到rows
的內部循環。 循環結構應該類似於for(j=i; j<=rows; j++)
。 在這個循環內打印星星。
注意:除了從i
迭代到rows
您還可以從 1 迭代到rows - i + 1
。
打印完一行的所有列后,移動到下一行,即打印新行。
很好的解釋來自https://codeforwin.org/2015/07/inverted-right-triangle-star-pattern-program-in-c.html
/**
* Reverse right triangle star pattern program in C
*/
#include <stdio.h>
int main()
{
int i, j, rows;
/* Input number of rows from user */
printf("Enter number of rows : ");
scanf("%d", &rows);
/* Iterate through rows */
for(i=1; i<=rows; i++)
{
/* Iterate through columns */
for(j=i; j<=rows; j++)
{
printf("* ");
}
/* Move to the next line */
printf("\n");
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.