for (初始化; 條件; 迭代) {
// 迴圈體
}
// 等價 while
初始化;
while (條件) {
// 迴圈體
迭代;
}
// 印出 1~10 偶數
for (int x = 1; x <= 10; x++) {
if (x % 2 == 1) continue; // 跳過奇數
System.out.println("x=" + x);
}
int sum = 0;
for (int x = 1; x <= 10; x++) {
sum += x;
}
System.out.println("sum=" + sum); // 55
int count = 0;
for (int x = 1; x <= 100; x++) {
if (x % 7 == 0) count++;
}
System.out.println("count=" + count); // 14
核心模式:累加變量 + 迴圈遍歷 + 條件判斷 + 計數器++。
for (int row = 0; row < 3; row++) { // 外層控制行數
for (int col = 0; col < 4; col++) { // 內層控制每行列數
System.out.print("*");
}
System.out.println(); // 換行
}
for (int row = 0; row < 5; row++) {
for (int col = row; col < 5; col++) { // 內層起始隨外層遞增
System.out.print("*");
}
System.out.println();
}
/*
*****
****
***
**
*
*/
// 正三角形
for (int row = 0; row < 5; row++) {
for (int col = 0; col <= row; col++) { // 列數隨行數遞增
System.out.print("*");
}
System.out.println();
}
// 數字三角形
for (int row = 1; row <= 5; row++) {
for (int col = 1; col <= row; col++) {
System.out.print(col);
}
System.out.println();
}
/*
1
12
123
1234
12345
*/
for (int row = 1; row <= 9; row++) {
for (int col = 1; col <= row; col++) {
System.out.print(col + "*" + row + "=" + (col*row) + "\t");
}
System.out.println();
}
int n = 5;
// 上半部
for (int row = 1; row <= n; row++) {
// 空格
for (int s = 0; s < n - row; s++) System.out.print(" ");
// 星號
for (int col = 1; col <= 2*row - 1; col++) System.out.print("*");
System.out.println();
}
// 下半部
for (int row = n - 1; row >= 1; row--) {
for (int s = 0; s < n - row; s++) System.out.print(" ");
for (int col = 1; col <= 2*row - 1; col++) System.out.print("*");
System.out.println();
}
/*
*
***
*****
*******
*********
*******
*****
***
*
*/
外層管行,內層管列。
尖朝上:內層條件 隨外層增大 (col <= row)。
尖朝下:內層起始值 隨外層增大 (col = row)。
對稱圖形:拆成上下兩個迴圈,第二個反向迭代。
for 迴圈是程式設計最基礎的控制結構。透過「累加、計數、巢狀列印圖形」三大經典練習,能建立對迴圈變數生命週期、邊界條件、巢狀層級關係的直覺理解。熟練掌握這些模式,是演算法與資料結構學習的敲門磚。