Scala while Loop
As long as the given condition is true, in the Scala languagewhilethe loop statement will repeatedly execute the block of code within the loop body.
Syntax
In the Scala languagewhilethe syntax of a while loop is:
while(condition)
{
statement(s);
}
Here,statement(s)it can be a single statement, or a block of code composed of several statements.
conditionmay be any expression, and it is true when it has any non-zero value. When the condition is true, the loop is executed. When the condition is false, the loop exits, and the program flow will continue to execute the next statement immediately following the loop.
Flowchart
Here,whilethe key point of the while loop is that the loop may not be executed even once. When the condition is false, the loop body is skipped, and execution directly proceeds to the next statement after the while loop.
Example
Example
def main(args: Array[String]) {
// local variable
var a = 10;
// while loop execution
while( a < 20 ){
println( "Value of a: " + a );
a = a + 1;
}
}
}
Executing the above code produces the following output:
$ scalac Test.scala $ scala Test value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19Other Extensions
Scala Loops