Iterating Through 2D Array Java

Java

We explored using for loops with one-dimensional arrays. Now let's jump into nested for loops as a method for iterating through 2D arrays. A nested for loop is one for loop inside another. Take a look below to see what this means.

Iteration2DExample.java

package exlcode;
 
public class Iteration2DExample {

  public static int[][] exampleVariableOne = {{0, 1, 2, 3, 4}, {4, 5, 6, 7, 8}};

  public static void main(String[] args) {
    // nested for loops are necessary for
    // iterating through a 2D array
    for (int countOne = 0; countOne < exampleVariableOne.length; countOne++) {
      for (int countTwo = 0; countTwo < exampleVariableOne[countOne].length; countTwo++) {
        System.out.print("Index [" + countOne + "][" + countTwo + "]: ");
        System.out.println(exampleVariableOne[countOne][countTwo]);
      }
    }
  }
}

The first for loop loops through each row of the 2D array one by one. As the first loop runs through each row, the second (nested) for loop inside the first loop loops through the columns one by one. The nested for loops runs row by row, checking each column within the row before moving on to the next row.

Because each row could have different numbers of columns, we need to access the specific column length of the specified row. That is why you see exampleVariableOne[countOne].length used within the second nested for loop.

The concept of using loops when working with 2D arrays is an essential tool in every programmer's toolkit. Look meticulously through the code above and become comfortable with how each loop fits into the big picture. When you become comfortable with the for loop, try using “for-each” loops with 2D arrays.


Related post

Python Dictionary with For Loop

Python, ,

Using the dictionary structure with for loops is incredibly efficient in python. In this card, I will show you some examples of ways to use dictionaries in for loops. The first example I am going to cover is expanding a dictionary into a list of lists. Lets imagine that you have a dictionary where the …

Read more
Nested Loops JavaScript

JavaScript,

A composition of loops is called a nested loop. The most common type of nested loops will be one loop inside another. The first loop is usually called the outer loop while the second loop is called the inner loop. The outer loop always executes first, and the inner loop executes inside the outer loop …

Read more