Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala

What are 'do while' loops in Scala?

Sheza Munir

In usual execution, the code is executed sequentially, line-by-line. Loops in Scala are control structures that allow users to run a block of code multiple times.

Do-while loop

The do-while loop repeatedly executes a block of code while the given condition stays true. It is different from the while loop in that it checks the condition after running the block of code.

Every do-while loop runs at least once, i.e. the block of code is executed, the condition is checked to run it again. If the condition holds true, it loops another time, otherwise, the loop execution terminates.

Syntax

do {
   //statement(s);
} 
while(condition);

Code

The following code shows an example of do-while loop in Scala where the value of the variable, myVal, is incremented and printed each time in the loop until its value becomes 5 after which it terminates since the loop condition evaluates to False.


object Educative
{
   def main(args:Array[String]) {
      // Local variable declaration:
      var myVal = 0;

      // do-while loop
      do {
         myVal = myVal + 1;
         println(myVal);
      } 
      while( myVal < 5 );

   }

}

RELATED TAGS

scala

CONTRIBUTOR

Sheza Munir
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring