Scala While Loops
A while loop repeats a block while its condition stays true. The block must change something, or the loop never ends.
A counter loop prints 1 to 3
The counter grows by one in each round. When it reaches 4, the condition turns false and the loop stops.
@main def main(): Unit =
var count = 1
while count <= 3 do
println(count)
count += 1A countdown loop runs backwards
This counter shrinks by one in each round. The loop stops when the counter drops below 1.
@main def main(): Unit =
var count = 3
while count >= 1 do
println(count)
count -= 1An accumulator builds a sum
The total starts at 0 and gains the counter value in each round. Printing after the loop shows the finished sum of 1 to 5.
@main def main(): Unit =
var total = 0
var i = 1
while i <= 5 do
total += i
i += 1
println(total)Example
@main def main(): Unit =
var week = 1
var savings = 0
while week <= 4 do
savings += 10
println(savings)
week += 1
println(s"Total: $savings")Key points
- While: the word while starts the loop and is followed by a condition.
- Do: the word do marks the end of the condition line in Scala 3.
- Repeat: the indented block runs again and again while the condition is true.
- Counter: a counter is a var that tracks how many rounds have run.
- Accumulator: an accumulator is a var that builds up a total across rounds.
- Ending: the loop stops as soon as the condition becomes false.
In this example, the loop runs once for each week from 1 to 4. Savings grows by 10 in each round, printing 10, 20, 30 and then 40. After the loop ends, the final line prints the total of 40.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
A while loop has the condition count < 3 and count starts at 0, growing by 1 each round. How many rounds run?