Arrays · Lesson 14 of 42
2D Arrays and Matrix Programs
A two-dimensional array is an array of arrays – perfect for anything laid out in rows and columns: a seating plan, a marks sheet with subjects as columns, a game board or a mathematical matrix. Matrix programs are a staple of campus coding tests, so this lesson ends with the four you are most likely to meet.
In this lesson
- Creating 2-D arrays and accessing
[row][col] - Nested loops over rows and columns
- Jagged arrays (rows of different lengths)
- Matrix addition, transpose, multiplication and spiral order
Creating a 2-D array
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[][] marks = {
{78, 85, 90}, // student 0: maths, science, english
{65, 72, 80}, // student 1
};
System.out.println(marks[1][2]); // row 1, column 2
System.out.println("rows: " + marks.length + ", cols: " + marks[0].length);
int[][] grid = new int[2][3]; // all zeros
grid[0][1] = 5;
System.out.println(Arrays.deepToString(grid));
}
}
80 rows: 2, cols: 3 [[0, 5, 0], [0, 0, 0]]
int[][] marks – an array of row arrays
- marks→ an array of 2 references
- marks[0] → [78, 85, 90]row 0 is itself an int[]
- marks[1] → [65, 72, 80]marks[1][2] is 80
Looping over rows and columns
public class Main {
public static void main(String[] args) {
String[] subjects = {"Maths", "Science", "English"};
int[][] marks = {{78, 85, 90}, {65, 72, 80}, {92, 88, 79}};
for (int s = 0; s < marks.length; s++) {
int total = 0;
for (int c = 0; c < marks[s].length; c++) total += marks[s][c];
System.out.println("Student " + (s + 1) + " total: " + total);
}
for (int c = 0; c < subjects.length; c++) {
int sum = 0;
for (int[] row : marks) sum += row[c];
System.out.printf("%s average: %.1f%n", subjects[c], sum / (double) marks.length);
}
}
}
Student 1 total: 253 Student 2 total: 217 Student 3 total: 259 Maths average: 78.3 Science average: 81.7 English average: 83.0
Jagged arrays
Because each row is a separate array, rows can have different lengths – useful for things like Pascal's triangle or attendance where months have different numbers of days:
public class Main {
public static void main(String[] args) {
int rows = 5;
int[][] pascal = new int[rows][];
for (int r = 0; r < rows; r++) {
pascal[r] = new int[r + 1];
pascal[r][0] = pascal[r][r] = 1;
for (int c = 1; c < r; c++) pascal[r][c] = pascal[r - 1][c - 1] + pascal[r - 1][c];
}
for (int[] row : pascal) {
StringBuilder sb = new StringBuilder();
for (int v : row) sb.append(v).append(' ');
System.out.println(sb.toString().trim());
}
}
}
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
Common mistake: assuming every row has the same length
Loop with matrix[r].length, not matrix[0].length, for the inner loop. With jagged arrays the second version throws ArrayIndexOutOfBoundsException or skips elements.
Matrix programs
Addition and transpose
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[][] a = {{1, 2, 3}, {4, 5, 6}};
int[][] b = {{6, 5, 4}, {3, 2, 1}};
int[][] sum = new int[2][3];
for (int i = 0; i < 2; i++)
for (int j = 0; j < 3; j++) sum[i][j] = a[i][j] + b[i][j];
System.out.println(Arrays.deepToString(sum));
int[][] t = new int[3][2]; // rows and columns swap
for (int i = 0; i < 2; i++)
for (int j = 0; j < 3; j++) t[j][i] = a[i][j];
System.out.println(Arrays.deepToString(t));
}
}
[[7, 7, 7], [7, 7, 7]] [[1, 4], [2, 5], [3, 6]]
Multiplication
For A (m × n) times B (n × p), each result cell is the dot product of a row of A and a column of B – three nested loops:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[][] a = {{1, 2}, {3, 4}};
int[][] b = {{5, 6}, {7, 8}};
int n = a.length, m = b[0].length, k = b.length;
int[][] c = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
for (int x = 0; x < k; x++) c[i][j] += a[i][x] * b[x][j];
System.out.println(Arrays.deepToString(c));
}
}
[[19, 22], [43, 50]]
Spiral order
A favourite of product-company interviews: walk the matrix in a spiral by shrinking four boundaries.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
int[][] m = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
List<Integer> out = new ArrayList<>();
int top = 0, bottom = m.length - 1, left = 0, right = m[0].length - 1;
while (top <= bottom && left <= right) {
for (int c = left; c <= right; c++) out.add(m[top][c]);
top++;
for (int r = top; r <= bottom; r++) out.add(m[r][right]);
right--;
if (top <= bottom) { for (int c = right; c >= left; c--) out.add(m[bottom][c]); bottom--; }
if (left <= right) { for (int r = bottom; r >= top; r--) out.add(m[r][left]); left++; }
}
System.out.println(out);
}
}
[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
Practice
Try it yourself
Print the sum of both diagonals of a 3 × 3 matrix {{1,2,3},{4,5,6},{7,8,9}}.
Show solution
public class Main { public static void main(String[] args) { int[][] m = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int primary = 0, secondary = 0; for (int i = 0; i < m.length; i++) { primary += m[i][i]; secondary += m[i][m.length - 1 - i]; } System.out.println(primary + " " + secondary); } }15 15
Rotate a 3 × 3 matrix 90° clockwise into a new matrix.
Show solution
import java.util.Arrays; public class Main { public static void main(String[] args) { int[][] m = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int n = m.length; int[][] r = new int[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) r[j][n - 1 - i] = m[i][j]; System.out.println(Arrays.deepToString(r)); } }[[7, 4, 1], [8, 5, 2], [9, 6, 3]]
Quick check
How do you get the number of columns in row 2 of grid?
grid[2].length
What is a jagged array?
A 2-D array whose rows have different lengths, possible because each row is a separate array.
How do you print a 2-D array's contents?
Arrays.deepToString(matrix)
Summary
- A 2-D array is an array of row arrays:
m[row][col]. - Loop rows with
m.lengthand columns withm[r].length; rows may differ (jagged). - Know addition, transpose, multiplication and spiral traversal for coding rounds.
Interview practice: Java coding interview programs.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.