Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Iterating Through 2D Array
AP® Computer Science A (Java) Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source AP® (Advanced Placement®) Java Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency. It is a substantial amount of coursework that represents a typical year of high school-level study or a semester of a University computer science course. This course may also be used to prepare for the AP® Computer Science A exam.
-->
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
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.