Monday, 31 August 2020

Scala: Nested for loops

Syntax

for {
   loop condition 1
   loop condition 2 
} {
    ......
    ......
    .....
}

Below snippet prints the multiplication table from 1 to 4.

for(int i = 1; i <= 2; i++){
    for(int j = 1; j <= 3; j++){
        System.out.println(i + " * " + j + " = " + i * j);
    }
}

Using nested for loops of Scala, you can write like below.

for{
     i <- 1 to 2
     j <- 1 to 3
   }
{
     val k = i * j
     println(s"$i * $j = $k")
}

scala> for{
     | i <- 1 to 2
     | j <- 1 to 3
     | }
     | {
     |  val k = i * j
     |  println(s"$i * $j = $k")
     | }
     | 
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6

You can even apply if condition in nested for loops.

scala> for{
     |      i <- 1 to 2
     |      j <- 1 to 3
     |      if (i != j)
     | }
     | {
     |      val k = i * j
     |      println(s"$i * $j = $k")
     | }
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
2 * 3 = 6




Previous                                                    Next                                                    Home

No comments:

Post a Comment