Multidimensional Arrays

2D Arrays

A 2D array is an array of arrays, like a table with rows and columns. Access an element with arr[row][col].

int[][] m = {{1, 2, 3},
              {4, 5, 6}};

           col 0  col 1  col 2
  row 0      1      2      3
  row 1      4      5      6        m[1][2] = 6

Example

public class Main {
    public static void main(String[] args) {
        int[][] m = {{1, 2, 3}, {4, 5, 6}};
        System.out.println("Rows: " + m.length + ", Cols: " + m[0].length);
        System.out.println("m[1][2] = " + m[1][2]);

        for (int r = 0; r < m.length; r++) {
            for (int c = 0; c < m[r].length; c++) {
                System.out.print(m[r][c] + " ");
            }
            System.out.println();
        }

        int[][] grid = new int[2][3];   // all zeros
        grid[0][1] = 9;
        for (int[] row : grid) {
            for (int v : row) System.out.print(v + " ");
            System.out.println();
        }
    }
}

Output

Rows: 2, Cols: 3
m[1][2] = 6
1 2 3 
4 5 6 
0 9 0 
0 0 0

Jagged Arrays

Example

Rows can have different lengths.

public class Main {
    public static void main(String[] args) {
        int[][] triangle = new int[4][];
        for (int i = 0; i < triangle.length; i++) {
            triangle[i] = new int[i + 1];
            triangle[i][0] = 1;
            triangle[i][i] = 1;
            for (int j = 1; j < i; j++) {
                triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
            }
        }
        for (int[] row : triangle) {
            for (int v : row) System.out.print(v + " ");
            System.out.println();
        }
    }
}

Output

1 
1 1 
1 2 1 
1 3 3 1

Note: This builds Pascal's triangle: each value is the sum of the two values above it.

Practice

Exercise: Find the sum of all elements in int[][] a = {{1, 2}, {3, 4}, {5, 6}}.

Show answer
int sum = 0;
for (int[] row : a) {
    for (int v : row) sum += v;
}
System.out.println(sum);   // 21