while and do-while: When to Use Each
Write while and do-while loops and understand their use cases.
Two Kinds of While Loops
Kotlin offers both while (pre-test) and do-while (post-test). The difference: do-while always runs the body at least once.
Basic while Loop
A while checks the condition before each iteration. If false initially, the body never runs.
fun main() {
var count = 0
while (count < 3) {
println("count = $count")
count++
}
}All lessons in this course
- for Loop Over Ranges and Collections
- while and do-while: When to Use Each
- forEach, repeat, and forEachIndexed
- break, continue, and Labeled Returns