Course Content
Introduction to Scala
Introduction to Scala
Iterating in 2D Arrays
Similarly to 1D arrays, iterating in 2D arrays allows us to traverse through rows and columns to access and manipulate elements or a fill an array based on a certain pattern.
Basic Iteration with Nested Loops
The most common way to iterate over a 2D array is using nested loops - one loop to iterate over the rows and another loop inside it to iterate over the columns of each row.
Let's take a look at an example where we use two for loops to print the elements of a 2D array:
Main
object Main { def main(args: Array[String]): Unit = { var matrix = Array( Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9) ) for (row <- matrix) { for (element <- row) { println(element) } } } }
In this example, we first print all the elements of the current row (inner 1D array), and then go to the next row.
Once again, the row
and element
variables are immutable (val
), so you cannot change their values.
Iterating with Indices
Another approach is to use indices for iteration, especially when you want to change the values of the elements.
Here is an example:
Main
object Main { def main(args: Array[String]): Unit = { var matrix = Array( Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9) ) for (i <- matrix.indices) { for (j <- matrix(i).indices) { matrix(i)(j) += 1 // Increases each element by 1 println(matrix(i)(j)) } } } }
In this example, we first increase each element by 1
and then print it.
We could use i <- 0 until matrix.length
for rows and j <- 0 until matrix(i).length
for columns, but the approach above is more concise. This approach, however, can be useful when we want to iterate only over certain indices, not all indices, for example:
Main
object Main { def main(args: Array[String]): Unit = { var matrix = Array( Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9) ) for (i <- 1 until matrix.length) { for (j <- 1 until matrix(i).length) { println(matrix(i)(j)) } } } }
Here, we printed only the elements in the second and third rows and the second and third columns.
Thanks for your feedback!