In this article, we will discuss about Scala while and do while loops. These loops are used to iterate statement or logic until the test condition is true.

Syntax , Examples and Differences between Scala while and do while loop

While loop will first verify test conditions and then execute logic, where as do while loop will first execute logic and then verify condition. So even if test condition fails do while loop assures that logic part are executed at least once.

1. Scala While loop & Do while loop

While loop starts with while keyword followed by test condition, if the condition is true then only logic or statements inside loop will be executed.

Syntax of Scala while loop  is as follows:

while (Test Condition) {

Statement / Logic

}

Let us try to code the factorial program using while loop. Here we will be creating a function for factorial calculation.

//file name : example1.scala

def factorial1={

println (“Enter the number”);

/* readInt() method is used to read

integer value from console */

val num=scala.io.StdIn.readInt();

println(num);

var n=1;

var fact=1;

while(n <= num){

                fact = fact * n;

                n=n+1;

               }

println(“factorial of “+num+” is “+fact);

}

factorial1 is a function that takes input from the user, and then display the results. We are using while loop to iterate till factorial is calculated.

// loading scala file

scala> :load example1.scala

Loading example1.scala…

factorial: Unit

// calling function

scala> factorial1

Enter the number

6

// function output

factorial of 6 is 720

Do while loop starts with do keyword followed by logic or statements and at last, there is while keyword followed by test condition.

Syntax of Scala do while loop is as follows:

do {

Statement / Logic

} while (Test Condition)

Let us try to code factorial program with do while loop.

//file name : example2.scala

def factorial2={

println (“Enter the number”);

val num=scala.io.StdIn.readInt();

println(num);

var n=1;

var fact=1;

do{

   fact = fact * n;

   n=n+1;

  }while(n <= num)

println(“factorial of “+num+” is “+fact);

}

In the above code, do while loop is used to run the iterations for calculating factorial. If we analyse example 1 & 2 , we will find there is not much difference in the code except the loop part.

// loading scala file

scala> :load example2.scala

Loading example2.scala…

factorial: Unit

// function calling

scala> factorial2

Enter the number

10

// function output

factorial of 10 is 3628800

We can also code factorial program using for loop and we have taken this example to understand the syntax. Now let us discuss the difference in next section.

Sql Server Clustering
Sql Server Clustering

2. Difference between Scala While and Do While loop

To understand the difference, let us write a program that takes any number of strings from user till  an empty string is entered. At last complete string is displayed as output.

While loop

//file name: example3.scala

def reading1 =

{

/* initializing a and input

to empty string*/

var a,input=””;

println (“please enter any String”);

/* readLine() method is used to read

string value from console */

input=scala.io.StdIn.readLine();// reading first string

a=a+input+” “;

println(input)

/* isEmpty() method will return Boolean ‘true’

as output if empty string is entered. */

while(!input.isEmpty()){

                        input=scala.io.StdIn.readLine();

                        a=a+input+” “;

                        println(input);

                       }

println(“You have Typed:”);

println(a);

}

In example 3, first string is read before while loop and other strings are read inside while block. When while loop is used then following logic is repeated in code(see example 3 : line 11 & 12, 17 & 18).

input=scala.io.StdIn.readLine();
a=a+input+” “;

We can avoid this problem by using do while. For now run the above code.

//loading scala file

scala> :load example3.scala

Loading example3.scala…

reading1: Unit

// calling function

scala> reading

please enter any String

Hello World

Welcome to HadoopTree

// Function output

You have Typed:

Hello World Welcome to Hadoop Tree

Now let us rewrite the example 3 code using do while and then analyze.

Do while loop

//file name : example4.scala

def reading2={

 var a,input=””;

 println (“please enter any String”);

 do{

    input=scala.io.StdIn.readLine();

    a=a+input+” “;

    println(input);

   }while(!input.isEmpty())

 println(“You have Typed:”);

 println(a);

}

If it is required that code should run at least once then do while is preferred.

Since user should at least enter first string in order to verify therefore do while loop eliminates the code repetition problem of example 2.

For more complex logic, there can be more lines of code, therefore do while loop keeps our code clean by avoiding repetitions and it is easy to maintain.

// loading scala file

scala> :load example4.scala

Loading example4.scala…

reading2: Unit

// calling function

scala> reading2

please enter any String

Hello

How are you?

// function output

You have Typed: Hello How are you?

Conclusion

We started our discussion with definition and syntax. Then we have discussed examples to understand the differences between while and do while.

I hope this article helped you in understanding the topic. Please share your thoughts via comments.