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

do-while Loop

A do-while loop does the action first and asks afterward whether to go again, like tasting soup and then deciding whether to keep cooking. So the action happens one time no matter what.

In this page:

  1. do-while Loop
Syntax
scala
do {
  // body
} while (condition)

do-while Loop

A do { ... } while (condition) loop checks its condition *after* running the body, guaranteeing the body executes at least once -- unlike while, which may skip the body entirely.

This construct is deprecated as of Scala 2.13 in favor of restructuring code with while or recursion, though it still compiles with a deprecation warning. It's useful to recognize in older Scala code even if avoided in new code.

Warning: do-while is deprecated since Scala 2.13 -- prefer a while loop with the condition check moved inside, or use recursion instead.

Example: do-while Loop

markup
object Main extends App {
  var count = 0

  do {
    println(s"Running iteration $count")
    count += 1
  } while (count < 3)
}
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. Expecting the body to be skipped when the condition is false at the start, when do-while always runs once.
  2. Forgetting to change the variable in the condition, creating an infinite loop.
  3. Using do-while in Scala 3 and finding it removed, when Scala 3 dropped do-while and you need while ({ ...; cond }) ().
🔒

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.