Easy Tutorial
❮ Functions Named Arguments Scala Lists ❯

Scala while Loop

Scala Loop Types

In Scala, the while loop statement will repeatedly execute the block of code within the loop as long as the given condition is true.


Syntax

The syntax for the while loop in Scala is:

while(condition)
{
   statement(s);
}

Here, statement(s) can be a single statement or a block of code consisting of several statements.

condition can be any expression that is true for any non-zero value. The loop is executed when the condition is true. When the condition is false, the loop is exited, and the program flow will continue with the statement immediately following the loop.


Flowchart

Here, the key point of the while loop is that the loop may not execute at all. When the condition is false, the body of the loop is skipped, and the next statement immediately following the while loop is executed.

Example

Example

object Test {
   def main(args: Array[String]) {
      // Local variable
      var a = 10;

      // Execution of while loop
      while( a < 20 ){
         println( "Value of a: " + a );
         a = a + 1;
      }
   }
}

The output of the above code is:

$ 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: 19

Scala Loop Types

❮ Functions Named Arguments Scala Lists ❯