What a while loop does
A while loop repeats a block of instructions for as long as a condition is true. Its shape is:
while (condition) {
instruction1
instruction2
// ...
}
Before every pass, Kotlin evaluates condition, which must be a Boolean. If it is true, the body runs once and Kotlin evaluates the condition again. If it is false, the loop ends and the program continues with the line after the closing brace. You can think of a while loop as an if statement that jumps back and checks again after every run.
An example
var count = 1
while (count <= 5) {
println("I made a mistake")
count++
}
println("Finished!")
The output is the message five times, followed by Finished!. Here is the loop traced step by step:
| Check | count | Condition | Result |
|---|---|---|---|
| 1 | 1 | 1 <= 5, true | prints, count becomes 2 |
| 2 | 2 | 2 <= 5, true | prints, count becomes 3 |
| 3 | 3 | 3 <= 5, true | prints, count becomes 4 |
| 4 | 4 | 4 <= 5, true | prints, count becomes 5 |
| 5 | 5 | 5 <= 5, true | prints, count becomes 6 |
| 6 | 6 | 6 <= 5, false | the loop ends |
The condition is checked six times and the body runs five times. The check that fails is what ends the loop. After that, println("Finished!") runs once.
The three parts of a counting loop
The update matters as much as the condition. A loop only ends if something inside it eventually makes the condition false, and for a counting loop that something is the counter.
Almost every counting while loop has the same three parts:
- Initialization. A variable that starts at a chosen value, written before the loop:
var count = 1. - Condition. A test, in the parentheses, that says whether to go on:
count <= 5. - Update. A change to the variable inside the body:
count++. Without it, the condition never changes.
Choosing the condition
The same pattern fits many tasks. Change the starting value, the condition or the update, and the loop does something different. To count from 1 to 5 you start at 1 and test <= 5. To count down you start high, test >= and subtract. When you design a loop, ask three questions: where does the variable start, when should the loop stop, and how does each pass move the variable toward that stop?
The exercise
The task is to print "I promise to learn coding." five times with a loop. The lesson builds it in four steps.
- Declare the counter. Write
var counter = 1. It must bevar, notval, because the loop will change it. Reassigning avalis a compile error. - Write the loop with its condition.
while (counter <= 5)lets the body run for the values 1, 2, 3, 4 and 5, which is five times. - Print inside the body.
println("I promise to learn coding.")runs on each pass. - Update the counter.
counter++adds 1 to the counter at the end of each pass. This is what eventually makes the condition false.
var counter = 1
while (counter <= 5) {
println("I promise to learn coding.")
counter++
}
Gotchas
- Forgetting the update. If
counter++is missing,counterstays 1, the condition1 <= 5is always true and the loop never ends. The program prints the message forever. This is an infinite loop. - Using
valfor the counter. The compiler rejectscounter++on avalwith the error'val' cannot be reassigned. - Off-by-one errors. Starting at 1 with
<= 5gives five passes. Starting at 0 with< 5also gives five. Mixing the two, such as starting at 1 with< 5, gives four. - A condition that is false at the start. The condition is checked before the first pass, so a
whileloop can run zero times. Withvar k = 5andwhile (k < 5), the body never runs. - The condition must be a
Boolean. Kotlin doesn't treat numbers as true or false, sowhile (counter)with anIntdoesn't compile. Write a comparison such ascounter <= 5. - The counter outlives the loop. It is declared before the loop, so it can be read after it. When the example above ends,
countis 6, the first value that made the condition false.
Key takeaways
while (condition) { ... }repeats its body as long as the condition is true.- The condition is checked before every pass, including the first.
- A counting loop needs a starting value, a condition and an update.
- Declare the counter with
var, and always make sure the body moves it toward the end of the loop.