๐ŸŽ“ A1Learner
๐Ÿ”

Kotlin For Loop

A for loop runs its block once for each value in a range or a string. The loop gives one value at a time in order.

Counting with a range

The range gives the loop its values in order. Each pass prints the current number.

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

Walking the letters of a word

A string gives the loop one letter at a time. The letters print in the order they appear in the word.

fun main() {
    for (letter in "code") {
        println(letter)
    }
}

Stepping through even numbers

step 2 in the range jumps by two on each pass. Starting at 2 makes every printed value even.

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

Building a total in a loop

A total starts at zero before the loop. Each pass adds the current value to the total.

fun main() {
    var sum = 0
    for (number in 1..4) {
        sum += number
    }
    println(sum)
}

Example

fun main() {
    var sum = 0
    for (number in 2..8 step 2) {
        sum += number
        println(number)
    }
    println(sum)
}

Key points

  • Use for with a name, the word in, and a range or a string.
  • The loop name holds the current value on each pass.
  • Each pass works with the next value in order.
  • A var changed inside the loop keeps its new value for the next pass.
  • Use step in a range to jump by the same gap on each pass.

In this example, sum starts at 0. The loop walks 2, 4, 6 and 8, and each pass adds its number to sum and prints the number. The last print shows sum as 20.

Note

The loop name is set fresh on each pass and cannot be changed inside the block.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

A total starts at 0. A loop adds 1, 2 and 3 to it in turn. What does the total hold after the loop?