Contenido del Curso
Introduction to Scala
Introduction to Scala
Do-while Loop
What is a `do-while` Loop?
Unlike the while loop, a do-while loop in Scala ensures that the code block inside it is executed first before the condition is checked, which means that this code is executed at least once . In other words, the condition may initially be false
, however, the code in the loop body will still be executed once.
Let's now take a look at the general syntax of such a loop:
Main
do { // Statement(s) to execute } while (condition);
As you can see, the only difference of this loop from a usual while loop is the fact that the condition is checked after the statements are executed. If it is true
, the program "returns" to the do
part and executes the statements once again. This process continues until the condition becomes false
.
Simple Countdown
Now it is time to take a look at some of the examples of using such loops. Let's start with a simple countdown program which prints numbers from 10
to 1
inclusive:
Main
object Main { def main(args: Array[String]): Unit = { var count = 10 // Starting point for the countdown do { println(count) count -= 1 // Decrements the counter } while (count > 0) println("Countdown finished!") } }
First, statements in the do
block are executed regardless of the condition, so the value of the count
variable is printed, and it is then decremented. Afterward, the condition (count > 0
) is checked. 9
is indeed greater than 0
, so the loop continues until i
becomes 0
, so it is not greater than 0
anymore, and the condition is thus false
.
The most appropriate use case for the do-while loop, however, is when you want to receive input from user until the user enters a certain character or a combination of characters. In this case, the condition should be checked after the input is received.
Input from User (optional)
When dealing with input from user, do-while loops really shine.
¡Gracias por tus comentarios!