Scala While Loop with Syntax and Example

1. Scala While Loop – Objective

In this Scala While Loop tutorial, we will study what is while loop in Scala with syntax and example. Moreover, we will discuss how Scala while loop works and One Infinite Loop with exmaple.

So, let’s start Scala while loop tutorial.

Scala While Loop with Syntax and Example

Scala While Loop with Syntax and Example

2. What is Scala While Loop?

A while loop that will execute a set of statements as long as a condition is true.

Scala While Loop

Scala While Loop

3. Working of While Loop in Scala

A Scala while loop first checks the condition. This may be any expression. Any non-zero value is true; zero is false.

So, if the condition is true, it executes the code in the block under it. The block of code may be one statement or more. Then, it checks the condition again. If still true, it executes the block of code again. Otherwise, it skips to the first statement outside the loop.

If the condition is false the first time, the loop skips to the first statement outside the loop, instead.

4. The syntax of While Loop

We have the following syntax for a Scala while loop:

while(condition)
{
//Code to execute if condition is true
}

5. Example of While Loop in Scala

Let’s build a loop that counts down from 7 to 1.

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

Here’s the output:
7
6
5
4
3
2
1
Initially, x is 7. The condition is initially true, because 7>0. The loop reduces it to 6. And so on, this loop runs as long as x reaches 1. Then, inside the loop’s body, it becomes 0. Now, when the condition is checked, it evaluates to false. So, it comes out of the loop.

Scala Quiz

6. One Infinite Loop

It is easy to forget putting in the statement that modifies the variable involved in the condition. This creates an infinite loop- one that never ends, because the condition is always true. Allow us to demonstrate using a while-loop.

import scala.util.control._
object Main extends App
{
    var a=0
    while(a<7)
    {
        print(a)
    }
}

This keeps printing 0 infinitely:
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

7. Conclusion

Hence, we discussed working, syntax and exmaple of while loop in Scala. At last, we covered one infinite loop.  Furthermore, if you have any query, feel free to share with us!

See you again with another basic to learn about. Good day.

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.