Google News
logo
Scala - Interview Questions
What is the difference between 'while' and 'do-while' loops in Scala?
In Scala, the `while` and `do-while` loops are used for repetitive execution of code blocks, but they have a slight difference in their loop structure and behavior:

1. `while` Loop : The `while` loop repeatedly executes a block of code as long as a given condition is true. It checks the condition before each iteration, and if the condition is false initially, the code block is not executed at all.
   var i = 0
   while (i < 5) {
     println(i)
     i += 1
   }​

   Output :
   0
   1
   2
   3
   4​

   In this example, the `while` loop iterates while `i` is less than 5. The `println(i)` statement is executed for each iteration, and `i` is incremented by 1. The loop terminates when the condition becomes false.
2. `do-while` Loop : The `do-while` loop also repeatedly executes a block of code, but it checks the condition after each iteration. This means that the code block is executed at least once, regardless of the condition's initial value.
   var i = 0
   do {
     println(i)
     i += 1
   } while (i < 5)​

   Output :
   0
   1
   2
   3
   4​

   In this example, the `do-while` loop starts by executing the code block, which includes the `println(i)` statement. Then, it checks the condition `i < 5`. If the condition is true, the loop continues to iterate. Otherwise, it terminates.

The key difference between the two loops is the timing of the condition check. In the `while` loop, the condition is checked before the first iteration, while in the `do-while` loop, the condition is checked after the first iteration.

Both `while` and `do-while` loops are useful for scenarios where you want to repeat a code block until a certain condition is met. However, it's important to ensure that the condition eventually becomes false to avoid infinite loops.
Advertisement