SCALA LOOPS With Examples

SCALA LOOPS :




For Loop:

A for loop is repetition control structure that allows   to efficiently write a loop that needs to execute a specific number of times.

Different types of for loop in SCALA:

  1. For Loop with Collections
  2. For Loop with Range
  3. For Loop with Filters
  4. For Loop with Yield.

For Loop with Collections: 

for (var <- List)

{

statement(y);

}

Here the List variable is a collection type having a list of elements and for loop iterate through all the elements returning one element in x variable at a time.

Example:

object ForLoopCollections{

def main (args: Array[String])

{

var x=0;

val numList = List(1,2,3,4,5);

for (x <-numList)

{

println(“Value of X:” +x)

}

}

}

For Loop with Range:

for (var x <- Range)

{

statement(y);

}

Here Range is the number of numbers that represented as I to J and   ” <-“means that “Generator” command as this operator only generating individual values from a range of numbers.

Example:

object ForLoopRange{

def main(args: Array[String])

{

var x = 0;

for (x <- 1 to 100)

{

println(“Value of X:” + x);

}

}

}

For Loop with Filters:

for ( var x <- List if conditions 1; if conditions 2; if conditions 3…)

{

statement(y);

}

}

Example:

object ForLoopFilterDemo{

def main(args: Array[String])

{

var x =0;

val numList = List (1,2,3,4,5,6,7,8,9);

for ( x <- numList if x!=5; if x < 9)

{

println(“Value of X:”+x);

}

}

}

For Loop with Yield:

val NorVal = for { var x <- List if condition 1; if condition 2….}

yield x

Here to store return values from a for loop in a variable or can return through a function.

Example:

object ForLoopYieldDemo{

def main(args: Array[String])

{

var x=0;

val numList = List(1,2,3,4,5,6,7,8,9);

val NorVal = for { x <- numList if x!=3; if x <9) yield a

for (x <- NorVal)

{

println(“Value of X”+x);

}

}

}

While Loop

Normally while loop statement repeatedly executes a target statement as long as a given condition is true.

while(condition)

{

statement(y);

}

Example:

object WhileLoopDemo{

def main(args: Array[String])

{

var x = 100;

while (x <300){

println (“Value of X:” +x);

x= x+1;

}

}

}

Do While Loop

Unlike while loop, which tests the loop condition at the top of the loop, the do while loop checks its condition at the bottom of the loop.




While and Do While loop is similar, except that a do while loop is guaranteed to execute at least one time.

Do

{

statement(y);

} while(condition);

Example:

object DoWhileLoopDemo{

def main(args: Array[String]{

var x =100;

do{

println (“Value of X :”+x);

x=x+1;

}while (x >300)

}

}