Iterating through a 2D Array
Now, let's talk about iterating through a 2D Array.
In a normal 1D Array, we can iterate one item at a time. However, with a 2D Array, we have two options:
- Row Major
- Column Major
In this lesson, we will be going through Row Major to iterate through an array.
What is Row Major?
Row Major is a way to iterate through 2D Arrays, allowing us to iterate by the arrays inside a 2D Array. We iterate by the row, as seen in the image below.
This is how it works:
- Open array[0], then items [0],[1],[2],[3],[4]
- Open array[1], then items [0],[1],[2],[3],[4]
- Open array[2], then items [0],[1],[2],[3],[4]
It goes one array at a time, going into the traditional iteration we know.
Here's how we would do it in Java:
int[][] values = {{-34,17,25,16,-2},{13,-4,12,8,15},{-21,6,2,3,14}};
for (int row = 0 ; row < values.length; row++) {
System.out.println("Array " + row); // prints the array
for (int col = 0; col < values[0].length; col++) {
System.out.println(values[row][col]); // prints the item
}
}
In Row Major, we use the first for loop to iterate through the arrays. In values, we have 3 of them.
Next, we use another for loop, also known as a nested for loop, to iterate and print the values/items in each array.
Row major is the most common way to iterate through a 2D Array. But is there another option?