Labs ICT
โญ Pro Login

For Loop

The for loop in Kotlin is built for iterating over ranges, arrays, and collections. It's clean, expressive, and nothing like the clunky C-style for you might remember.

Looping over a range

Use .. to create a range from start to end (inclusive).


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

This prints 1, 2, 3, 4, 5. The range 1..5 includes both ends.

Try it Yourself โ†’

Counting down with downTo

Need to go backwards? Use downTo.


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

Prints 5, 4, 3, 2, 1.

Try it Yourself โ†’

Skipping with step

Use step to skip values in a range.


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

Prints 1, 3, 5, 7, 9. You can combine step with downTo too.

Try it Yourself โ†’

Looping through a collection

for also works directly on lists, arrays, and anything iterable.


fun main() {
  val fruits = listOf("Apple", "Banana", "Cherry")
  for (fruit in fruits) {
    println(fruit)
  }
}
    

No index variable needed. Just clean iteration.

Try it Yourself โ†’

๐Ÿงช Quick Quiz

What keyword iterates over a range in Kotlin?