Home »
Scala
Nested loops in Scala
By IncludeHelp Last updated : October 10, 2024
In programming, a nested loop is used in initializing or iterate multi-dimensional array or to print patterns. Scala provides an efficient method to use nested loops in the programming language. The most used nested loop in programming is nesting of for loops. As in nesting, the loop body should be simple it is perfect for nesting.
Nested loop
Nested Loops in Scala, Looping through a 2-D structure required the use of nested loops. The multiple for loop has more than one counter that is used in order to make sure that efficient work is done by the counter.
Syntax
For nesting loops, we can place the second loop inside the body of the first loop. This is the traditional way and most used one too. And is done like this,
loop1{
loop2{
//code to be executed…
}
}
Example of Nested for loop
object MyClass {
def main(args: Array[String]) {
var i , j = 0;
for(i <- 1 to 2){
for(j <- 1 to 2)
println("(" + i + "," + j + ")")
}
}
}
Output
(1,1)
(1,2)
(2,1)
(2,2)
In this code two for loops are used to print tuples. The first runs from 1 to 2 and then the second run from 1 to 2 for each iteration of the first loop. For the first iteration of loop 1, loop 2 runs two times printing value 1,1 and 1,2. The same happens for the second iteration of loop 1 that prints 2,1 and 2,2.
Easier Way
In Scala, there is an easier way to make nested loops and this one requires fewer lines of code to be written by the programmer. The one uses multiple loop variable initialization in one body. Making use of this type reduces code length and is quick. This one is coded like this.
loop(coditionvar1 ; condtionvar2){
//body of the loop
}
Example
object MyClass {
def main(args: Array[String]) {
var i , j = 0;
for(i <- 1 to 2 ; j <- 1 to 2){
println("(" + i + "," + j + ")")
}
}
}
Output
(1,1)
(1,2)
(2,1)
(2,2)
The output is the same as above (1,1); (1,2);…. This is code in a lesser number of lines and only one block is used that reduces programming errors.
Explanation
The code works in the same way as it does for two loops. The loop first increments the value of counter 2 (j in this case) until it gets to the maximum possible value (2). Then it increases the counter 1 ( i ) and resets the second counter value to initial value. This continues till the counter 1's value is maxed out.
Another Way
Some other ways to write nested loops:
for{
i <- 1 to 10;
J <- 1 to 10;
} // code