Kotlin for Loop

Kotlin for Loop

In Kotlin, the for loop is used to iterate over ranges, arrays, lists, strings, and other collections. It is simple, powerful, and more flexible than traditional loops.


1. Basic for Loop (Range)

fun main() {
for (i in 1..5) {
println(i)
}
}

Output:

1
2
3
4
5

2. for Loop with until

for (i in 1 until 5) {
println(i)
}

Output:

1
2
3
4

(5 is excluded)


3. for Loop with step

for (i in 1..10 step 2) {
println(i)
}

Output:

1
3
5
7
9

4. Reverse Loop (downTo)

for (i in 5 downTo 1) {
println(i)
}

5. Loop Through an Array

val fruits = arrayOf("Apple", "Banana", "Mango")

for (fruit in fruits) {
println(fruit)
}


6. Loop with Index

for (i in fruits.indices) {
println("Index $i = ${fruits[i]}")
}

7. Using withIndex()

for ((index, value) in fruits.withIndex()) {
println("Index $index = $value")
}

8. Loop Through a String

for (ch in "Kotlin") {
println(ch)
}

9. break and continue in for Loop

for (i in 1..5) {
if (i == 3) continue
if (i == 5) break
println(i)
}

10. Nested for Loop

for (i in 1..3) {
for (j in 1..2) {
println("i=$i, j=$j")
}
}

Summary

  • for loop iterates over ranges and collections

  • No traditional for(init; condition; update)

  • Supports step, downTo, until

  • Clean and readable syntax

You may also like...