while and do-while Loops
In this page:
The while Loop
while repeatedly runs its body as long as the condition remains true, checking the condition before every iteration -- including the very first one.
Example: The while Loop
fun main() {
var count = 0
while (count < 5) {
println("Count is $count")
count++
}
}
Login to try C/C++/Java/PHP code in the editor
The do-while Loop
do-while runs its body first and checks the condition afterward, guaranteeing the body executes at least once even if the condition is false from the start.
Example: The do-while Loop
fun main() {
var attempts = 0
do {
println("Attempt number ${attempts + 1}")
attempts++
} while (attempts < 3)
}
Login to try C/C++/Java/PHP code in the editor
Infinite Loops with break
while (true) combined with a break statement inside the body creates a loop whose exit condition is easier to express in the middle of the logic rather than up front.
Note: Always make sure a while (true) loop has a reachable break, or it will run forever.
Example: Infinite Loops with break
fun main() {
var n = 1
while (true) {
println("n is $n")
n *= 2
if (n > 20) break
}
}
Login to try C/C++/Java/PHP code in the editor
Choosing Between while and do-while
Use while when the body might legitimately need to run zero times, and do-while when the body must always run at least once before checking whether to continue.
Example: Choosing Between while and do-while
fun main() {
val condition = false
while (condition) {
println("This never prints")
}
do {
println("This always prints once")
} while (condition)
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting to update the loop's condition variable inside the body, causing an infinite loop that never terminates.
- Using
whilewhen ado-whileis actually needed, resulting in a block that should run at least once being skipped entirely when the condition starts false. - Confusing the check order:
whilechecks before running the body,do-whilechecks after, changing how many times the body might run.
whilechecks its condition before each iteration, so the body may run zero times.do-whilechecks its condition after each iteration, guaranteeing the body runs at least once.- Both loops require the condition to eventually become false, usually by updating a variable inside the body.
while (true) { ... break ... }is a common pattern for loops whose exit condition is easier to express inside the body.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: