Kotlin For Loop

Kotlin For Loop

In Kotlin, the for loop is used to iterate through arrays, ranges, and other collections of data.

Unlike Java or C, Kotlin does not use a traditional for (int i=0; i<10; i++) syntax. Instead, it uses the in operator.


Looping Through an Array

To loop through the elements of an array, use the for loop together with the in operator:

Example

fun main() {
  val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
  for (car in cars) {
    println(car)
  }
}

In the example above, during the first iteration, the car variable holds the value "Volvo", the second iteration holds "BMW", and so on.


Looping Through a String

Because Strings are essentially sequences of characters, you can loop through them as well!

for (chars in "Hello") { println(chars) }