The while loop
- Kotlin course
- Beginner
- Lesson 43/116
- 4 min
Learn loops that run while a condition holds with while.
The while loop
The while loop runs a block as long as a condition is true. The condition is checked at the top; if false, the block never runs.
var n = 3
while (n > 0) {
println(n)
n = n - 1
}This prints 3, 2, 1. Each step n decreases by one; when n reaches 0, the condition becomes false and the loop ends.
We must update the loop variable ourselves; otherwise an infinite loop occurs. Make sure the condition eventually becomes false.
while with a counter
It is common to keep a counter in a while loop. The counter is updated each step; the condition depends on it.
var count = 0
while (count < 3) {
println("Step $count")
count = count + 1
}This prints "Step 0", "Step 1", "Step 2". When count reaches 3, the condition is false. var is used because the counter changes.
Forgetting to update the condition causes an infinite loop; the program hangs.
Practice Count down from 5 to 1
Write a fun main(). Assign 5 to var n. Use a while (n > 0) loop to print println(n) and decrease with n = n - 1 each step. The output should be 5, 4, 3, 2, 1.
Starter code
fun main() {
// Count down from 5 to 1
}Sample solution
fun main() {
var n = 5
while (n > 0) {
println(n)
n = n - 1
}
}Expected output
5 4 3 2 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the while behavior
| Term | Meaning |
|---|---|
condition true |
Runs the block |
condition false |
Ends the loop |
condition always true |
Infinite loop |
condition false at start |
Never runs |
2 while (x > 10) { ... } — x = 5: what happens?
- Runs the block
- Never runs Correct answer
- Infinite loop
- Throws error
Explanation: 5 > 10 is false, so the block never runs.
3 Complete the while condition
while (count ____ 3) { println(count) }
while (count < 3) { println(count) }
Explanation: count < 3 runs for 0, 1, 2.