What this lesson covers
A while loop repeats its body as long as its condition is true. Two things decide what it prints: where the counter starts, and how the counter changes on each pass. This lesson changes both. It steps by 2 instead of 1, and it counts down instead of up.
Stepping by 2
To print the even numbers from 4 through 14, start the counter at 4 and add 2 on every pass:
var i = 4
while (i <= 14) {
println(i)
i += 2
}
It prints 4, 6, 8, 10, 12 and 14, one per line. The condition i <= 14 uses <= because 14 itself must be printed. After 14 is printed, i becomes 16, the condition is false, and the loop ends.
Counting down
To go in reverse, start high, subtract in the body, and flip the comparison:
var i = 12
while (i >= 4) {
println(i)
i -= 2
}
This prints 12, 10, 8, 6 and 4. A condition written as i <= 4 would be false on the very first check, so the loop would never run.
Scala has no ++ or -- operators. Use i += 1 and i -= 1, or a larger step as above. The counter has to be a var, because a val can't be reassigned.
The assignment: odd numbers from 23 down to 7
The task is to print 23, 21, 19, and so on down to 7. Build it from the two patterns above.
- Declare the counter.
var counter = 23starts at the first number to print. It is odd, so stepping by 2 keeps it odd. - Write the loop with the right condition. The loop goes down and must include 7, so the condition is
counter >= 7. - Print the counter with
println(counter)inside the body. - Move to the previous odd number.
counter -= 2does it. Without this line the counter would never change and the loop would never end.
var counter = 23
while (counter >= 7) {
println(counter)
counter -= 2
}
The output is 23, 21, 19, 17, 15, 13, 11, 9 and 7, each on its own line. After 7 is printed the counter becomes 5, the condition fails and the loop stops.
Common mistakes
- Using
>instead of>=. Withcounter > 7the loop stops before printing 7. - Starting on the wrong parity. Starting at 22 and subtracting 2 would print even numbers. The starting value decides which numbers appear.
- Adding instead of subtracting.
counter += 2makes the counter grow away from 7, so the condition stays true forever. - Printing before or after the update. Moving
counter -= 2aboveprintlnwould print 21 first and skip 23.
Key takeaways
- The start value, the condition and the update together decide what a
whileloop prints. - Count down by subtracting in the body and using
>=or>in the condition. - Scala uses
+=and-=; it has no++. - Always check that the update moves the counter toward the point where the condition becomes false.
