4.2 2D Arrays and Sequence Statistics
A two-dimensional array can represent a table, matrix, grid, or board. It has row and column indexes.
int[][] grid = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(grid[1][2]); // 6grid[1][2] means: take row 1, then take column 2 inside that row. Both indexes start from 0.
Rows and columns
For a rectangular 2D array:
int[][] scores = new int[3][4];The first number is the row count, and the second number is the column count.
System.out.println(scores.length); // 3 rows
System.out.println(scores[0].length); // 4 columns in row 0Java 2D arrays are arrays of arrays. That means each row has its own length. Most beginner problems use rectangular arrays, but Java can also represent ragged arrays:
int[][] triangle = {
{1},
{1, 2},
{1, 2, 3}
};In a ragged array, triangle[0].length, triangle[1].length, and triangle[2].length are different.
Nested loops
Matrix addition can be done with nested loops. The outer loop controls rows, and the inner loop controls columns.
Matrix addition and subtraction require two matrices with the same shape. If A and B are both m x n matrices, then the result matrix is also m x n. "Element by element" means row i, column j is only combined with row i, column j from the other matrix.
int[][] a = {
{1, 3},
{1, 0},
{1, 2}
};
int[][] b = {
{0, 0},
{7, 5},
{2, 1}
};
int[][] c = new int[3][2];
System.out.println("Matrix Addition");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
c[i][j] = a[i][j] + b[i][j];
System.out.printf("%3d", c[i][j]);
}
System.out.println();
}Result:
Matrix Addition
1 3
8 5
3 3Statistics over arrays
Common array statistics include sum, average, maximum, and minimum.
int[] scores = {88, 91, 76, 95, 83};
int max = scores[0];
for (int i = 1; i < scores.length; i++) {
if (scores[i] > max) {
max = scores[i];
}
}For 2D arrays, decide whether the statistic belongs to one row, one column, or the whole table.
int row = 1;
int sum = 0;
for (int col = 0; col < scores[row].length; col++) {
sum += scores[row][col];
}
double average = sum / (double) scores[row].length;