Nested Loops with 2D Arrays
Part of the Logic & Flow section of Coddy's Java journey — lesson 3 of 59.
When working with 2D arrays, we often use nested loops to iterate over each row and each column, allowing us to access or modify every element in the array.
Here's a typical structure of nested loops for a 2D array:
for (int i = 0; i < array.length; i++) {
// Outer loop iterates over rows
for (int j = 0; j < array[i].length; j++) {
// Inner loop iterates over columns
// Access or modify array[i][j]
}
}The outer loop iterates over the rows, and the inner loop iterates over the columns of each row. This way, you can access each element in the 2D array by using array[i][j].
Challenge
EasyCreate a method named printMatrix that takes a 2D array of integers as an argument and prints its elements in a matrix format. Use nested loops to iterate over the rows and columns of the array.
Cheat sheet
Use nested loops to iterate over 2D arrays. The outer loop iterates over rows, and the inner loop iterates over columns:
for (int i = 0; i < array.length; i++) {
// Outer loop iterates over rows
for (int j = 0; j < array[i].length; j++) {
// Inner loop iterates over columns
// Access or modify array[i][j]
}
}Access each element using array[i][j] where i is the row index and j is the column index.
Try it yourself
// Write your code only inside the class. Do not write main() or any code outside this class.
class PrintMatrix {
public static void printMatrix(int[][] matrix) {
// Write your code here
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap