C 程式預設由 main() 起始,自上而下循序執行。但實際開發中極少單純循序執行,必須透過流程控制語句(if、for、while、do-while)改變執行順序,實現判斷與迴圈邏輯。
for (初始化運算式; 條件判斷; 遞增運算式) {
陳述句; // 單一或複合陳述句
}
#include
#include
int main() {
for (int i = 1; i <= 20; i++) {
printf("%d\n", i);
}
system("pause");
return 0;
}

for (int i = 20; i >= 1; i--) {
printf("%d\n", i);
}

int i = 0;
for (; i <= 20; i += 2) { // 初始化已在迴圈外完成
printf("%d\n", i);
}

int i = 0;
for (; i <= 20;) {
printf("%d\n", i++); // 後置遞增
}

int i = 0, j = 15;
for (; i <= 20 && j >= 0;) {
j--;
printf("%d\n", i++);
}

for(;;) 為無限迴圈)。#include
#include
void draw_box(int row, int column) {
int col;
for (; row > 0; row--) {
for (col = column; col > 0; col--) {
printf("x");
}
printf("\n");
}
}
int main() {
draw_box(8, 25); // 8行25列
system("pause");
return 0;
}

while (條件判斷) {
陳述句;
}
#include
#include
int main() {
int count = 1;
while (count <= 20) {
printf("%d\n", count);
count++;
}
system("pause");
return 0;
}

for (; condition;) 等價於 while (condition)。兩者可相互轉換,差異在於初始化與遞增的書寫位置。
#define _CRT_SECURE_NO_WARNINGS
#include
int main() {
int array[5];
int ctr = 0, nbr = 0;
printf("請輸入 5 個 1-10 之間的整數:\n");
while (ctr < 5) {
nbr = 0;
while (nbr < 1 || nbr > 10) {
printf("輸入第 %d 個數: ", ctr + 1);
scanf("%d", &nbr);
}
array[ctr] = nbr;
ctr++;
}
for (ctr = 0; ctr < 5; ctr++) {
printf("Value %d is %d\n", ctr + 1, array[ctr]);
}
system("pause");
return 0;
}

do-while 保證迴圈本體至少執行一次,條件判斷在本體之後:
do {
陳述句;
} while (條件判斷);
適用於選單驅動程式、輸入驗證等必須先執行一次的情境。
| 迴圈類型 | 適用場景 | 特點 |
|---|---|---|
| for | 已知迴圈次數、計數器控制 | 初始化、條件、遞增集中,結構清晰 |
| while | 未知迴圈次數、條件驅動 | 僅條件判斷,初始化與遞增分散 |
| do-while | 至少執行一次、選單/輸入驗證 | 後測試,保證首次執行 |
實務上,根據邏輯清晰度與可讀性選擇,必要時可相互轉換。