๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

Kotlin While Loop

A while loop repeats a block while its condition stays true. The condition is checked before each run of the block.

A counter ends the loop

The counter starts at 1 and grows on each run. The loop stops when the counter passes 3.

fun main() {
    var count = 1
    while (count <= 3) {
        println(count)
        count++
    }
}

A false condition runs zero times

The counter starts past the limit the condition allows. The line after the loop still prints and shows the counter unchanged.

fun main() {
    var count = 5
    while (count <= 3) {
        println(count)
        count++
    }
    println(count)
}

do-while runs at least once

The condition is false from the start in this program. The counter still reaches 1 because the block runs before the check.

fun main() {
    var runs = 0
    do {
        runs++
    } while (runs < 0)
    println(runs)
}

A while loop builds a total

Each run adds the counter to a running total. The print after the loop shows the finished total.

fun main() {
    var number = 1
    var total = 0
    while (number <= 4) {
        total += number
        number++
    }
    println(total)
}

Example

fun main() {
    var left = 3
    while (left > 0) {
        println(left)
        left--
    }
    println(left)
}

Key points

  • while: a loop that repeats while a condition stays true.
  • Use while with a condition and a block in braces.
  • A counter changed inside the block can make the condition false.
  • A while loop with a false first condition runs zero times.
  • do-while: a loop that checks its condition after the block.

In this example, left starts at 3. The loop prints left and then lowers it by 1 on each run. The loop prints 3 and 2 and 1 in order. The condition fails when left reaches 0 and the loop ends. The last print shows 0.

Note

A condition that never becomes false makes the loop run without end.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

A do-while loop adds 1 to a counter that starts at 0. Its condition is counter < 0. What does the counter hold after the loop?