Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Iterating in 2D Arrays | Arrays
Introduction to Scala
course content

Conteúdo do Curso

Introduction to Scala

Introduction to Scala

1. Getting Started
2. Variables and Data Types
3. Conditional Statements and Loops
4. Arrays
5. Strings

bookIterating 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:

java

Main

copy
1234567891011121314
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:

java

Main

copy
123456789101112131415
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:

java

Main

copy
1234567891011121314
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.

What will be printed?

What will be printed?

Selecione a resposta correta

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 4. Capítulo 5
some-alt