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:
Syntax
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
object Main extends App {
var count = 0
do {
println(s"Running iteration $count")
count += 1
} while (count < 3)
}
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
- Expecting the body to be skipped when the condition is false at the start, when
do-whilealways runs once. - Forgetting to change the variable in the condition, creating an infinite loop.
- Using
do-whilein Scala 3 and finding it removed, when Scala 3 droppeddo-whileand you needwhile ({ ...; cond }) ().
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: