Types of Loops in Scala

Loop is used to execute the block of code several times according to the condition given in the loop. It means it executes the same code multiple times so it saves code and also helps to traverse the elements of the array.
There are 3 types of the loop –

We have the perfect professional Scala and Apache Spark Training Course for you!

Watch this Spark-Scala video

Scala Loops Types of Loops in Scala Loop is used to execute the block of code several times according to the condition given in the loop. It means it executes the same code multiple times so it saves code and also helps to traverse the elements of the array. There are 3

  • while Loop –

While loop execute the code until condition is false.
Syntax

while(condition){
//code
}

while loopWish to get certified in Scala! Learn Scala from top Scala experts and excel in your career with Intellipaat’s Scala certification!
e.g.

object Intellipaat {
def main(args: Array[String]) {
var I = 20;
while( a >10 ){
println( "Value of I is: " + I );
I = I - 2;
}
}
}

Compile and execute the above program:
scalac Intellipaat.scala
scala Intellipaat
Output
Value of I is:20
Value of I is:18
Value of I is:16
Value of I is:14
Value of I is:12
 

  • do – while loop

It also executes the code until the condition is false. In this at least once, code is executed whether the condition is true or false, but this is not the case with a while. While the loop is executed only when the condition is true.

Go through this Scala training in London to get a clear understanding of Scala!

 Syntax

do
{
//code
}while(condition);

e.g.

object Intellipaat {
def main(args: Array[String]) {
var I = 20;
do{
println( "Value of I is: " + I );
I = I - 2;
} while( a >10 );
}
}

Compile and execute the above program:
scalac Intellipaat.scala
scala Intellipaat
Output
Value of I is:20
Value of I is:18
Value of I is:16
Value of I is:14
Value of I is:12
Value of I is:10

  • for loop

It also executes the code until a condition is false. It is used when the number of iterations is known where while is used when the number of iterations is not known.

Prepare yourself for the industry by going through this Top Apache Spark and Scala Interview Questions and Answers!

Syntax

for( var I <- Range ){
//code
}

e.g.

object Intellipaat {
def main(args: Array[String]) {
var I = 0;
for (I <- 1 to 10){
println( "Value of I is: " + I );
I = I + 2;
}
}
}

Compile and execute the above program:
scalac Intellipaat.scala
scala Intellipaat
Output
Value of I is:1
Value of I is:3
Value of I is:5
Value of I is:7
Value of I is:9
This blog will help you get a better understanding of Significance Of Scala!

Recommended Videos

Leave a Reply

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

Solve : *
17 + 21 =