Beginner 6 min readKotlin 2.0
Kotlin while and do-while Loops
while repeats a block as long as a condition is true. do-while runs the block at least once, then checks the condition.
What You Will Learn
- while loop syntax and use
- do-while loop
- Difference between while and do-while
- Infinite loops and how to stop them
while Loop
while checks the condition before each iteration.
while Loop
kotlin
fun main() {
var count = 1
while (count <= 5) {
println(count)
count++
}
}Output
1
2
3
4
5
count starts at 1. Each iteration prints count and increments it. When count becomes 6, the condition is false and the loop ends.
Common Mistake: Forgetting to update the loop variable inside the loop causes an infinite loop. Always ensure the condition will eventually become false.
do-while Loop
do-while executes the block once before checking the condition.
do-while
kotlin
fun main() {
var n = 0
do {
println("n = $n")
n++
} while (n < 3)
}Output
n = 0
n = 1
n = 2
The body runs with n=0, then the condition n < 3 is checked. The loop continues while the condition is true.
break and continue
break exits the loop immediately. continue skips to the next iteration.
break and continue
kotlin
fun main() {
for (i in 1..10) {
if (i == 4) continue // skip 4
if (i == 7) break // stop at 7
print("$i ")
}
}Output
1 2 3 5 6
continue skips 4. break stops the loop when i reaches 7. 7 itself is not printed.
Practice Exercise
Exercisepredict output
What prints? var x = 10 while (x > 7) { println(x) x-- }
Quick Quiz
Quick Quiz
What is the key difference between while and do-while?
Frequently Asked Questions
Related Tutorials
Last updated: 2026-05-01Kotlin 2.0
Written by KotlinGuide Editorial Team ยท Reviewed by KotlinGuide Technical Review