Repeat while a condition remains true.

loop A `while` loop checks its condition before each pass through the block.

While Loop

target
WhileLoop.kt
Replay: real traced execution (multi-file project)
fun main() {
    val target = 4
    var current = 1
    var steps = 0

    while (current < target) {
        current += 1
        steps += 1
    }

    println("current=$current")
    println("steps=$steps")
}
fun main() {
    val target = 2
    var current = 1
    var steps = 0

    while (current < target) {
        current += 1
        steps += 1
    }

    println("current=$current")
    println("steps=$steps")
}
fun main() {
    val target = 6
    var current = 1
    var steps = 0

    while (current < target) {
        current += 1
        steps += 1
    }

    println("current=$current")
    println("steps=$steps")
}
  1. target ← 4, current ← 1, steps ← 0

    1fun main() {2    val target→ 4 = 4 //@target=2, 63    var current→ 1 = 14    var steps→ 0 = 0
  2. current ← 2, steps ← 1

    pass 1 of 3
    6while (current1 < target4) {7    current→ 2 += 18    steps→ 1 += 19}
    All 3 passes — pass 1 is the card above
    passcurrentsteps
    11 20 1
    22 31 2
    33 42 3
  3. println("current=$current")

    11    println("current=$current4")12    println("steps=$steps3")13}
    outputcurrent=4
    steps=3
  1. target ← 2, current ← 1, steps ← 0

    1fun main() {2    val target→ 2 = 23    var current→ 1 = 14    var steps→ 0 = 0
  2. current ← 2, steps ← 1

    6while (current1 < target2) {7    current→ 2 += 18    steps→ 1 += 19}
  3. println("current=$current")

    11    println("current=$current2")12    println("steps=$steps1")13}
    outputcurrent=2
    steps=1
  1. target ← 6, current ← 1, steps ← 0

    1fun main() {2    val target→ 6 = 63    var current→ 1 = 14    var steps→ 0 = 0
  2. current ← 2, steps ← 1

    pass 1 of 5
    6while (current1 < target6) {7    current→ 2 += 18    steps→ 1 += 19}
    All 5 passes — pass 1 is the card above
    passcurrentsteps
    11 20 1
    22 31 2
    33 42 3
    44 53 4
    55 64 5
  3. println("current=$current")

    11    println("current=$current6")12    println("steps=$steps5")13}
    outputcurrent=6
    steps=5

Follow the While Loop

  1. target starts as 4.
  2. current starts at 1.
  3. The loop runs while current < target.
  4. Each pass adds 1 to current and 1 to steps.
  5. The loop stops at current=4 after 3 steps. | pass | current after | steps after | | --- | --- | --- | | start | 1 | 0 | | 1 | 2 | 1 | | 2 | 3 | 2 | | 3 | 4 | 3 |

Exercise: WhileLoop.kt

Reproduce current=4 and steps=3, then use the pinned target variants 2 and 6 to predict current=2 steps=1 and current=6 steps=5.