Scala do while Loop | A Quick and Easy Tutorial

1. Scala do while loop

Today, we will learn a new topic called Scala Do While Loop, which belongs to Scala control loop statement. Here, we will learn the syntax and example of do while loops. Along with this, we will discuss the working of Do While loop in Scala?

So, let’s start Scala do while loop.

Scala do while Loop | A Quick and Easy Tutorial

Scala do while Loop | A Quick and Easy Tutorial

2. What is Scala do While Loop?

A Scala do while loop will execute a set of statements as long as a condition is true. This is like a while-loop. However, there are two differences:

  1. A while-loop checks the condition before entering the loop. A do-while loop checks it after executing the loop.
  2. This means that a do-while loop will execute at least once. But a while loop may never run.
Scala do - while loop flow chart

Scala do – while loop flow chart

3. Working of Do While Loop in Scala

A Scala do while loop first executes the loop once. Then, it checks the condition, which may be any expression. While zero means false, any non-zero value is true.

The rest of the working is like a while-loop. If the condition is true, it executes the code block under itself. It can be one or more statements. Next, it checks the condition again. If true, it executes the block again. Otherwise, it skips to the first statement outside the do-while loop.

Even if the condition is false for the first time, the loop still runs at least once.

4. A Syntax of Scala Do-While Loop

This is the syntax for a do-while loop in Scala:

do
{
statement(s);
}
while(condition);
Scala Quiz

5. Scala Do While Loop Examples

Let’s count down from 7 to 1.

object Main extends App
{
   var x=7
    do
    {
        println(x)
        x=x-1
    }while(x>0);

Here’s the output:
7
6
5
4
3
2
1

Initially, x is 7. The loop executes the loop once. This makes x equal to 6. Then, it checks the condition. Now since 6>0, the condition is true. So, it executes the body yet again. This goes on until x becomes 1. The loop’s body makes it 0. Then, it checks the condition, which is now false. Hence, it comes out of the loop.

Note that this code works even if you skip the semicolon after the while.

Now, let’s take the case when the condition is never true:

object Main extends App
{
    var x=0
    do
    {
        println(x)
        x=x-1
    }while(x>0)
}

See? It runs at least once.

6. Conclusion

So, that’s all we have for Scala do while loops. Stay tuned for more Scala loops tutorial. Furthermore, if you have any query, feel free to ask in the comment box.

Reference

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.