迴圈#

以下是 Kotlin 迴圈(Loop): forwhiledo-while 的基本用法。


1. for 迴圈#

for 迴圈用於遍歷集合、區間或執行固定次數的操作。

基本語法#

1
2
3
for (變數 in 集合或範圍) {
    // 執行的程式碼
}

範例 1:遍歷區間#

1
2
3
4
5
fun main() {
    for (i in 1..5) {
        println(i) // 輸出:1, 2, 3, 4, 5
    }
}
  • 1..5 表示從 1 到 5(包含 5)的閉區間。
  • downTo 表示遞減範圍。
  • step 指定步長。

範例:

1
2
3
4
5
fun main() {
    for (i in 5 downTo 1 step 2) {
        println(i) // 輸出:5, 3, 1
    }
}

範例 2:遍歷集合#

1
2
3
4
5
6
fun main() {
    val items = listOf("蘋果", "香蕉", "櫻桃")
    for (item in items) {
        println(item)
    }
}

範例 3:帶索引遍歷集合#

使用 withIndex 同時取得索引與值。

1
2
3
4
5
6
fun main() {
    val items = listOf("蘋果", "香蕉", "櫻桃")
    for ((index, item) in items.withIndex()) {
        println("索引 $index 的值是 $item")
    }
}

2. while 迴圈#

while 迴圈會先檢查條件,然後執行迴圈內的程式碼。

基本語法#

1
2
3
while (條件) {
    // 執行的程式碼
}

範例 1:計數器#

1
2
3
4
5
6
7
fun main() {
    var x = 5
    while (x > 0) {
        println(x) // 輸出:5, 4, 3, 2, 1
        x--
    }
}

範例 2:條件控制#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
fun main() {
    var sum = 0
    var i = 1

    while (i <= 10) {
        sum += i
        i++
    }

    println("總和是 $sum") // 總和是 55
}

3. do-while 迴圈#

do-while 迴圈會先執行程式碼一次,然後再檢查條件。

基本語法#

1
2
3
do {
    // 執行的程式碼
} while (條件)

範例 1:執行一次後檢查條件#

1
2
3
4
5
6
7
fun main() {
    var x = 0
    do {
        println(x) // 輸出:0
        x++
    } while (x < 1)
}

4. 控制迴圈流程#

break#

break 用於跳出整個迴圈。

1
2
3
4
5
6
7
8
fun main() {
    for (i in 1..5) {
        if (i == 3) {
            break
        }
        println(i) // 輸出:1, 2
    }
}

continue#

continue 用於跳過當前的迭代,直接進入下一次迴圈。

1
2
3
4
5
6
7
8
fun main() {
    for (i in 1..5) {
        if (i == 3) {
            continue
        }
        println(i) // 輸出:1, 2, 4, 5
    }
}

標籤與嵌套迴圈#

在 Kotlin 中,可以用標籤跳出嵌套迴圈。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
fun main() {
    outer@ for (i in 1..3) {
        for (j in 1..3) {
            if (i == 2 && j == 2) {
                break@outer // 跳出 outer 迴圈
            }
            println("i = $i, j = $j")
        }
    }
}

輸出:

1
2
3
4
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1

5. 用集合操作代替迴圈#

Kotlin 提供許多高階函式(如 mapfilterforEach),可以取代傳統迴圈,讓程式更簡潔。

1
2
3
4
5
fun main() {
    val numbers = listOf(1, 2, 3, 4, 5)
    val squares = numbers.map { it * it }
    println(squares) // 輸出:[1, 4, 9, 16, 25]
}

Reference#

https://kotlinlang.org/docs/control-flow.html#for-loops

https://kotlinlang.org/docs/control-flow.html#while-loops

https://kotlinlang.org/docs/returns.html#break-and-continue-labels

https://kotlinlang.org/docs/basic-syntax.html#for-loop

https://kotlinlang.org/docs/ranges.html#progression

© 2026 CodeReindeer. All rights reserved.