Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FOR LOOP Multiple Generators

Tags:

scala

Problems understanding how the code below works. I am new to Scala and have been learning the language for 2 weeks now.

for (i <- 1 to 3; j <- 1 to 3) print((10 * i + j) + " ")

it prints 11 12 13 21 22 23 31 32 33. Does it assign each value in turn i.e.

i = 1

j = 0

or does the values get assigned each time it loops i.e.

i = 1

j = 1

Thanks

like image 879
jeniffer_214 Avatar asked Sep 25 '26 11:09

jeniffer_214


1 Answers

It's just nested loop for j. So, for each assigned value of i, all values of j are iterated.

for (i <- 1 to 3) {
  for (j <- 1 to 3) {
    print((10 * i + j) + " ")
  }
}

Because a for loop expands to foreach, your code is also equivalent to:

(1 to 3).foreach { i =>
  (1 to 3).foreach { j =>
    print((10 * i + j) + " ")
  }
}

Maybe in this form, it's more easy to see.

like image 161
alno Avatar answered Sep 28 '26 03:09

alno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!