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

while Loop

In this page:

  1. while Loop

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")
}
🔒

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.