While Loop in Scala

Scala While loop is used to iterate a block of statements over a condition. The condition is a boolean expression.

In this tutorial, we will learn how to write while loop in Scala with example programs.

Syntax – While Loop

The syntax of Scala while loop is

while(boolean_expression){
     statement(s)
 }

When the program control comes to while loop, it first checks if the boolean expression evaluates to true. If true the statement(s) inside the while block are executed and the boolean expression is evaluated. If it evaluates to true, the statements are executed and the process continues with checking the boolean expression. The while loop is executed until the boolean expression is true. When the expression evaluates to false, the program control comes out of the while loop statement and continues with the subsequent statements.

The variables used in the boolean expression have to be updated explicitly inside the while loop.

Example 1 – Scala While Loop

In this example, we shall find the square of a number until it is less than 10 and print the result to the console.

example.scala

object WhileLoopExample {
  def main(args: Array[String]) {
    var i=0
    while (i < 10){
      var square = i*i
      println(square)
      // update i
      i=i+1
    }
  }
}

Output

1
4
9
16
25
36
49
64
81

If you forget to update the variable i inside the while loop, the loop becomes infinite loop and the program control will be trapped inside it. The control will never come out of the loop and no subsequent statements are executed ever.

Conclusion

In this Scala Tutorial, we learned what a while loop is, the syntax of while loop in Scala, and its usage with the help of examples.