while Loop
A while loop keeps repeating as long as a condition is true, like refilling a glass until it is full. It checks the condition before each round.
In this page:
Syntax
while (condition) {
// body
}
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting to update the loop variable, so
while (n > 1)runs forever. - Using a
valfor the counter, when it must be avarto change inside the loop. - Expecting
whileto return a value, when it is a statement that returnsUnit.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: