Control Flow
While Loop
Repeat while a condition remains true.
loop
A `while` loop checks its condition before each pass through the block.
While Loop
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")
}
target ← 4, current ← 1, steps ← 0
1fun main() {2 val target→ 4 = 4 //@target=2, 63 var current→ 1 = 14 var steps→ 0 = 0current ← 2, steps ← 1
pass 1 of 36while (current1 < target4) {7 current→ 2 += 18 steps→ 1 += 19}All 3 passes — pass 1 is the card above pass currentsteps1 1 → 2 0 → 1 2 2 → 3 1 → 2 3 3 → 4 2 → 3 println("current=$current")
11 println("current=$current4")12 println("steps=$steps3")13}outputcurrent=4 steps=3
target ← 2, current ← 1, steps ← 0
1fun main() {2 val target→ 2 = 23 var current→ 1 = 14 var steps→ 0 = 0current ← 2, steps ← 1
6while (current1 < target2) {7 current→ 2 += 18 steps→ 1 += 19}println("current=$current")
11 println("current=$current2")12 println("steps=$steps1")13}outputcurrent=2 steps=1
target ← 6, current ← 1, steps ← 0
1fun main() {2 val target→ 6 = 63 var current→ 1 = 14 var steps→ 0 = 0current ← 2, steps ← 1
pass 1 of 56while (current1 < target6) {7 current→ 2 += 18 steps→ 1 += 19}All 5 passes — pass 1 is the card above pass currentsteps1 1 → 2 0 → 1 2 2 → 3 1 → 2 3 3 → 4 2 → 3 4 4 → 5 3 → 4 5 5 → 6 4 → 5 println("current=$current")
11 println("current=$current6")12 println("steps=$steps5")13}outputcurrent=6 steps=5
Follow the While Loop
targetstarts as4.currentstarts at1.- The loop runs while
current < target. - Each pass adds
1tocurrentand1tosteps. - The loop stops at
current=4after3steps. | 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.