Traversing 2D Arrays
Traversing 2D Arrays
Traversing Defined
- Traversing is the process of examining every element in an array, typically to perform a specific task or operation on each of them.
Why Traverse?
- Traversing a 2D array is important for a variety of tasks, such as searching for a specific value or modifying each value.
Nested Loop Traversal
- Nested loops are the most common way to traverse a 2D array, with an outer loop iterating over rows and an inner loop iterating over each column in a given row.
- Remember – in Java, a 2D array is essentially an array of arrays, so double iteration makes sense.
Sample Traversal Code
- A basic example might look like this:
for(int i = 0; i < array.length; i++){ for(int j = 0; j < array[i].length; j++){ // Perform tasks with array[i][j] here } }
This code example will iterate over every element in the 2D array.
Row-Major Versus Column-Major
- The order in which you traverse a 2D array – rows first (as above), or columns first – can matter, depending on what you need to do with the array.
- If you need to traverse column by column instead of row by row, reverse the order of your loops:
for(int j = 0; j < array[0].length; j++){ for(int i = 0; i < array.length; i++){ // Perform tasks with array[i][j] here } }
This will iterate over each column first before moving to the next row.
Traversal Pitfalls
- Be aware that attempting to access an element outside the bounds of a 2D array will result in an
ArrayIndexOutOfBoundsException
error in your code. - Keep careful track of your index variables to ensure you do not try to access a row or column that does not exist.
- Always use
array.length
orarray[row].length
when looping over your array to avoid indexing errors.