Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Do-while Loop | Conditional Statements and Loops
Introduction to Scala
course content

Contenido del Curso

Introduction to Scala

Introduction to Scala

1. Getting Started
2. Variables and Data Types
3. Conditional Statements and Loops
4. Arrays
5. Strings

bookDo-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:

java

Main

copy
1234
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:

java

Main

copy
12345678910111213
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.

What will be printed? (print(count + " "  simply prints the value of the count variable and adds a space to the output)

What will be printed? (print(count + " " simply prints the value of the count variable and adds a space to the output)

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 3. Capítulo 5
some-alt