# Kotlin for循環

Kotlin `for`循環用於迭代程序的一部分幾次。 它遍歷數組，範圍，集合或提供迭代的任何內容。 Kotlin `for`循環等同於C#等語言中的`foreach`循環。

Kotlin中`for`循環的語法如下：

``````for (item in collection){
// 循環的主體
}``````

#### 迭代數組

``````fun main(args : Array<String>) {
val marks = arrayOf(80,85,60,90,70)
for(item in marks){
println(item)
}
}``````

``````80
85
60
90
70``````

``````fun main(args : Array<String>) {
val marks = arrayOf(80,85,60,90,70)
for(item in marks)
println(item)
}``````

``````80
85
60
90
70``````

``````fun main(args : Array<String>) {

val marks = arrayOf(80,85,60,90,70)
for(item in marks.indices)
println("marks[\$item]: "+ marks[item])
}``````

``````marks[0]: 80
marks[1]: 85
marks[2]: 60
marks[3]: 90
marks[4]: 70``````

#### 迭代範圍

``````fun main(args : Array<String>) {

print("for (i in 1..5) print(i) = ")
for (i in 1..5) print(i)
println()
print("for (i in 5..1) print(i) = ")
for (i in 5..1) print(i)             // prints nothing
println()
print("for (i in 5 downTo 1) print(i) = ")
for (i in 5 downTo 1) print(i)
println()
print("for (i in 5 downTo 2) print(i) = ")
for (i in 5 downTo 2) print(i)
println()
print("for (i in 1..5 step 2) print(i) = ")
for (i in 1..5 step 2) print(i)
println()
print("for (i in 5 downTo 1 step 2) print(i) = ")
for (i in 5 downTo 1 step 2) print(i)
}``````

``````for (i in 1..5) print(i) = 12345
for (i in 5..1) print(i) =
for (i in 5 downTo 1) print(i) = 54321
for (i in 5 downTo 2) print(i) = 5432
for (i in 1..5 step 2) print(i) = 135
for (i in 5 downTo 1 step 2) print(i) = 531``````
0 條評論，你可以發表評論，我們會進行改進