while and do-while
A for loop is perfect when you know what to walk through. But "keep brewing while there are beans" has no list: you only know when to stop. That is the job of while.
The rule
while checks, then acts; do-while acts, then checks.
var beans = 50
var cups = 0
while (beans >= 18) {
beans -= 18
cups++
}
println("$cups cups, $beans g left") // 2 cups, 14 g leftThe condition is tested before each round. If it is false at the start, the body runs zero times.
do-while flips the order: the body runs first, then the condition decides whether to go again. So the body always runs at least once:
do {
val size = readln()
println("You chose $size")
} while (size !in listOf("S", "M", "L"))This is the natural shape for "ask, and ask again if the answer was bad". Kotlin has a neat detail here: a variable declared inside the do body, like size, is visible in the while condition.
Every while loop needs something inside it that moves toward stopping, here beans -= 18. Forget it and the condition never changes, giving an infinite loop.
cups++ adds 1 to a var; cups-- subtracts 1. Both work only on variables, not on vals.
The shortcut
Before writing a loop, answer two questions: "Must the body run at least once?" (yes → do-while, no → while) and "Which line makes the condition eventually false?" If you cannot point to that line, the loop may never end.
Start
beans = 50. Is 50 ≥ 18? Yes, so run the body:beans = 32,cups = 1.
Drills
Answer fast — trust the rule.
var n = 0; while (n > 0) { n-- }. How many times does the body run?
var n = 0; do { n++ } while (n > 5). What is n afterwards?
Which loop never ends?
var t = 100; while (t >= 30) { t -= 30 }. What is t afterwards?
Remember
whilechecks first and may run zero times;do-whilealways runs once.- Point to the line that makes the condition false, or risk an endless loop.
- Use
do-whilefor "try, then retry if needed".
