Scala While Loop

A while loop repeats a block of code as long as a condition remains true. In Scala, while loops are used less frequently than in Java or Python — functional alternatives like recursion and collection methods are usually preferred. But while loops are useful for situations that genuinely require mutable state and imperative-style repetition.

Basic While Syntax

var count = 1

while count <= 5 do
  println(s"Count: $count")
  count += 1

// Count: 1
// Count: 2
// Count: 3
// Count: 4
// Count: 5

Start: count = 1

count <= 5?  Yes → print, count becomes 2
count <= 5?  Yes → print, count becomes 3
count <= 5?  Yes → print, count becomes 4
count <= 5?  Yes → print, count becomes 5
count <= 5?  Yes → print, count becomes 6
count <= 5?  No  → exit loop

While Loop Anatomy

while condition do
  body statement 1
  body statement 2
  ...

// In Scala 2 style (also valid in Scala 3):
while (condition) {
  body
}

Countdown Example

var n = 10
while n > 0 do
  print(s"$n ")
  n -= 1
println("Go!")
// 10 9 8 7 6 5 4 3 2 1 Go!

Reading Until a Sentinel Value

// Simulated input: processing until -1 signals stop
val inputs = List(5, 12, 3, -1, 8)   // -1 is the stop signal
var index = 0
var total = 0

while inputs(index) != -1 do
  total += inputs(index)
  index += 1

println(s"Sum: $total")   // Sum: 20

Accumulating a Result

var sum = 0
var i = 1

while i <= 100 do
  sum += i
  i += 1

println(s"Sum of 1 to 100: $sum")   // 5050

while with Multiple Conditions

var x = 1
var y = 10

while x < 5 && y > 6 do
  println(s"x=$x, y=$y")
  x += 1
  y -= 1

// x=1, y=10
// x=2, y=9
// x=3, y=8
// x=4, y=7

The do-while Loop

A do-while loop runs the body at least once before checking the condition. Scala 3 uses a different syntax compared to most languages:

// Scala 3 do-while
var attempt = 0

do
  attempt += 1
  println(s"Attempt $attempt")
while attempt < 3

// Attempt 1
// Attempt 2
// Attempt 3

The difference from a regular while: the body runs first, then the condition is checked. Even if the condition starts as false, the body runs once.

Infinite Loop (Use with Care)

// Example: server polling loop (conceptual)
var running = true
var ticks = 0

while running do
  ticks += 1
  println(s"Tick $ticks")
  if ticks >= 3 then running = false

// Tick 1
// Tick 2
// Tick 3

While Loop vs Recursion

Scala's functional style prefers recursion over while loops for many tasks. Here is the same computation both ways:

// While loop (imperative)
def sumToN_while(n: Int): Int =
  var total = 0
  var i = 1
  while i <= n do
    total += i
    i += 1
  total

// Recursion (functional)
def sumToN_rec(n: Int): Int =
  if n <= 0 then 0 else n + sumToN_rec(n - 1)

// Collection method (most Scala-idiomatic)
def sumToN_col(n: Int): Int = (1 to n).sum

println(sumToN_while(10))   // 55
println(sumToN_rec(10))     // 55
println(sumToN_col(10))     // 55

Building a String with While

val word = "Scala"
var result = ""
var pos = word.length - 1

while pos >= 0 do
  result += word(pos)
  pos -= 1

println(result)   // alacS

In practice, you would write word.reverse. The while version shows how the loop works step by step.

Nested While Loops

var row = 1
while row <= 3 do
  var col = 1
  while col <= 4 do
    print(f"${row * col}%3d")
    col += 1
  println()
  row += 1

//   1  2  3  4
//   2  4  6  8
//   3  6  9 12

When to Use While in Scala


Good use cases for while:
  ✓ Reading input until a stop signal
  ✓ Game loops with mutable state
  ✓ Performance-critical inner loops where recursion overhead matters
  ✓ Interoperating with Java APIs that use mutable iteration

Prefer alternatives when:
  ✗ Iterating over a collection → use foreach, map, filter
  ✗ Building a result → use foldLeft or recursion
  ✗ Simple counting → use for loop or (1 to n).foreach

Common Mistake: Infinite Loop

// BUG: forgot to increment counter
var i = 0
while i < 5 do
  println(i)
  // i += 1  ← missing!  → runs forever!

// ALWAYS make sure the loop body moves toward the exit condition

An infinite loop freezes your program. Always verify that the variable controlling the condition changes inside the loop body and that it will eventually make the condition false.

Leave a Comment

Your email address will not be published. Required fields are marked *