algoritmauzmanı
Sign in
TREN
2.3Multidimensional Arrays
Lesson 2.3.1

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 . In this lesson you declare a with 3 rows and 4 columns, traverse it with two nested loops and find the sum of each row.

What you will learn
  • 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
6 minTime O(n·m)Memory O(n)C · Java · Python

1Idea

In a two-dimensional array every element has two : 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 0
matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]empty = [[0] * 4 for _ in range(3)]  # 3 rows, 4 columns, all 0

To 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.

i = 0i = 1i = 2j = 0j = 1j = 2j = 31234567891011121sums[0]10sums[0]26sums[1]42sums[2]ij
  1. The matrix is declared: 3 rows, 4 columns. m[1][2] is 7, in row 1, column 2.
  2. The outer loop picks the first row with i = 0 and sums[0] is set to 0. The inner loop starts with j = 0 and adds m[0][0], which is 1.
  3. The inner loop moves j up to 3: 1 + 2 + 3 + 4 = 10. When j reaches 4 the inner loop ends.
  4. The outer loop moves to the second row with i = 1 and the inner loop starts again from j = 0: 5 + 6 + 7 + 8 = 26.
  5. The same happens for i = 2: 9 + 10 + 11 + 12 = 42.
  6. 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 sums

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(n·m)

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.

Memory
O(n)

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 . 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 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];?

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]?

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.