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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With