Scala Tutorial Scala References

Scala - While Loop



A loop statement allows a program to execute a given block of codes repeatedly under a given condition. This enables a programmer to write programs in fewer lines of code and enhance the code readability. Scala has following types of loop to handle the looping requirements:

The While Loop

A while loop allows a set of statements to be executed repeatedly as long as a specified condition is true. The while loop can be viewed as a repeating if statement.

Syntax

while (condition) {
  statements
}

Flow Diagram:

Scala While Loop

In below mentioned example, program uses while loop to sum all integers from 1 to 5.

object MainObject {
  def main(args: Array[String]) {
    var i = 0
    var sum = 0
    while (i <= 5) {
      sum = sum + i
      i += 1
    }
    println(sum) 
  }
}

The output of the above code will be:

15

The Do-While Loop

The do-while loop is a variant of while loop which execute statements before checking the conditions. Therefore the do-while loop executes statements at least once.

Syntax

do {
  statements
}
while (condition)

Flow Diagram:

Scala Do-While Loop

In the example below, even if the condition is not fulfilled, the do-while loop executes the statements once.

object MainObject {
  def main(args: Array[String]) {
    var i = 10
    var sum = 0
    do {
      sum = sum + i
      i += 1
    }
    while (i <= 5)
    println(sum) 
  }
}

The output of the above code will be:

10