← Back to Scala Course | Chapter 4: Control Flow | Lesson 2 of 7

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:

  1. while Loop
Syntax
scala
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

markup
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")
}
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
  1. Forgetting to update the loop variable, so while (n > 1) runs forever.
  2. Using a val for the counter, when it must be a var to change inside the loop.
  3. Expecting while to return a value, when it is a statement that returns Unit.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.