萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Java for 迴圈完整練習:巢狀迴圈、累加計數、星號圖形、九九乘法表

基礎語法回顧


for (初始化; 條件; 迭代) {
    // 迴圈體
}
// 等價 while
初始化;
while (條件) {
    // 迴圈體
    迭代;
}

1. 語句巢狀與 continue


// 印出 1~10 偶數
for (int x = 1; x <= 10; x++) {
    if (x % 2 == 1) continue; // 跳過奇數
    System.out.println("x=" + x);
}

2. 累加求和與計數器模式

2.1 1~10 求和


int sum = 0;
for (int x = 1; x <= 10; x++) {
    sum += x;
}
System.out.println("sum=" + sum); // 55

2.2 1~100 中 7 的倍數個數


int count = 0;
for (int x = 1; x <= 100; x++) {
    if (x % 7 == 0) count++;
}
System.out.println("count=" + count); // 14

核心模式:累加變量 + 迴圈遍歷 + 條件判斷 + 計數器++。

3. 巢狀迴圈圖形列印

3.1 長方形 (3 行 × 4 列)


for (int row = 0; row < 3; row++) {       // 外層控制行數
    for (int col = 0; col < 4; col++) {   // 內層控制每行列數
        System.out.print("*");
    }
    System.out.println(); // 換行
}

3.2 直角三角形 (尖朝下)


for (int row = 0; row < 5; row++) {
    for (int col = row; col < 5; col++) { // 內層起始隨外層遞增
        System.out.print("*");
    }
    System.out.println();
}
/*
*****
****
***
**
*
*/

3.3 正三角形 / 楊輝三角雛形 / 數字三角形


// 正三角形
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
*/

3.4 九九乘法表


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();
}

4. 菱形 (金字塔) — 綜合練習


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 迴圈是程式設計最基礎的控制結構。透過「累加、計數、巢狀列印圖形」三大經典練習,能建立對迴圈變數生命週期、邊界條件、巢狀層級關係的直覺理解。熟練掌握這些模式,是演算法與資料結構學習的敲門磚。

copyright © 萬盛學電腦網 all rights reserved