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.
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.
do {
//statement(s);
}
while(condition);
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 loopdo {myVal = myVal + 1;println(myVal);}while( myVal < 5 );}}
Free Resources