2.3Multidimensional Arrays
Two-dimensional arrays
A grade sheet, a game board or the pixels of an image are made of rows and columns. To store them you use a two-dimensional array. In this lesson you declare a matrix with 3 rows and 4 columns, traverse it with two nested loops and find the sum of each row.
- How to declare a two-dimensional array in C, Java and Python and reach an element with
m[i][j] - Traversal where the outer loop walks the rows and the inner loop the columns
- Two common mistakes: building a matrix by list multiplication in Python and passing a matrix to a function in C
1Idea
In a two-dimensional array every element has two indices: m[i][j] is in row i, column j. Both indices start at 0. In a 3×4 matrix the rows go from 0 to 2 and the columns from 0 to 3; the last element is m[2][3].
In the three languages the same matrix is declared like this:
int matrix[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};int[][] empty = new int[3][4]; // 3 rows, 4 columns, all 0matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]empty = [[0] * 4 for _ in range(3)] # 3 rows, 4 columns, all 0To visit every element you write two nested loops. The outer loop walks the rows with i, the inner loop walks the columns of that row with j. For the sum of a row, the inner loop adds up that row's elements.
In Java every row is a separate array; the number of rows is matrix.length and the length of row i is matrix[i].length. Python uses len(matrix) and len(matrix[i]). In C an array does not store its own size; you have to know the number of rows and columns from a constant or a parameter.
2Step by step
The drawing finds the row sums of a 3×4 matrix holding the numbers 1 to 12. The labels on the left are row indices, the ones at the bottom column indices.
- The matrix is declared: 3 rows, 4 columns.
m[1][2]is 7, in row 1, column 2. - The outer loop picks the first row with
i = 0andsums[0]is set to 0. The inner loop starts withj = 0and addsm[0][0], which is 1. - The inner loop moves
jup to 3: 1 + 2 + 3 + 4 = 10. Whenjreaches 4 the inner loop ends. - The outer loop moves to the second row with
i = 1and the inner loop starts again fromj = 0: 5 + 6 + 7 + 8 = 26. - The same happens for
i = 2: 9 + 10 + 11 + 12 = 42. - The outer loop is done. Every element was read exactly once and the three row sums are ready.
#define ROWS 3#define COLS 4 void rowSums(int matrix[][COLS], int rows, int sums[]) { for (int i = 0; i < rows; i++) { // each row sums[i] = 0; for (int j = 0; j < COLS; j++) // each column in the row sums[i] += matrix[i][j]; }}int[] rowSums(int[][] matrix) { int[] sums = new int[matrix.length]; // one per row for (int i = 0; i < matrix.length; i++) { // each row sums[i] = 0; for (int j = 0; j < matrix[i].length; j++) // each column in the row sums[i] += matrix[i][j]; } return sums;}def row_sums(matrix): sums = [0] * len(matrix) # one per row for i in range(len(matrix)): # each row sums[i] = 0 for j in range(len(matrix[i])): # each column in the row sums[i] += matrix[i][j] return sumsThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
In a matrix with n rows and m columns the body of the inner loop runs n·m times; each element is read once. For a 3×4 matrix that is 12 steps.
One sum is kept per row, an array of n elements. The matrix itself is the input and is not counted.
For a square matrix (n×n) this is O(n²). Any operation that looks at every element of a matrix takes at least this long.
4Common mistake
The most common mistake when building a matrix of zeros in Python is this:
m = [[0] * 4] * 3 # wrong: all three rows are one listm[0][0] = 5print(m) # [[5, 0, 0, 0], [5, 0, 0, 0], [5, 0, 0, 0]]* 3 does not copy the inner list; it puts three references to the same list. Change one row and all three change. The right way is to build a new list for each row; the definition of empty above does this with a list comprehension.
In C, when you pass a two-dimensional array to a function, the number of columns must be written. void f(int m[][]) does not compile; void f(int m[][COLS], int rows) does. The compiler has to know how many elements one row takes in order to compute the address of m[i][j]. The reason is in Row-major and column-major order.
5Try it
Which is the last element of the array int a[3][4];?
The answer is B. Indices start at 0. The rows are 0, 1, 2 and the columns 0, 1, 2, 3. a[3][4] is outside the array.
Show the answer
The answer is B. Indices start at 0. The rows are 0, 1, 2 and the columns 0, 1, 2, 3. a[3][4] is outside the array.
In Python you write row = [0] * 3, m = [row] * 2 and then m[0][1] = 7. What is m[1][1]?
The answer is B. [row] * 2 puts the same list in twice. m[0] and m[1] are the same list, so the change shows up in both.
Show the answer
The answer is B. [row] * 2 puts the same list in twice. m[0] and m[1] are the same list, so the change shows up in both.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.