while Loop
In this page:
while Loop
A while loop checks its condition before every iteration and keeps running as long as it's true. Unlike for, a while loop itself is a statement that produces Unit, not a useful value. It's used when the number of iterations isn't known ahead of time, though idiomatic Scala often prefers higher-order functions or recursion over while where practical.
Warning: Forgetting to update the loop variable inside the body creates an infinite loop, the same risk as in most other languages.
Example: while Loop
object Main extends App {
var n = 20
var steps = 0
while (n > 1) {
n = if (n % 2 == 0) n / 2 else n * 3 + 1
steps += 1
}
println(s"Reached 1 in $steps steps")
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: