To visit every element in a D array, you nest two loops. The outer loop walks through rows, and the inner loop walks through columns:
int[][] grid = {
{1, 2, 3},
{4, 5, 6}
};
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[r].length; c++) {
System.out.print(grid[r][c] + " ");
}
System.out.println();
}
grid.length gives the number of rows. grid[r].length gives the number of columns in row r. Using grid[r].length instead of a hardcoded number protects you from out-of-bounds errors if rows have different lengths.
You can also use nested for-each loops when you do not need the indices:
for (int[] row : grid) {
for (int val : row) {
System.out.print(val + " ");
}
System.out.println();
}