Two-dimensional arrays

The 2D array: rows and columns, m[i][j] access, nested loops, traversal by rows, by columns or along a diagonal, neighbours of a cell and array of arrays.

  • 26 cards
  • 6 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. The numbers
  5. Scenarios
  6. Understand

A few cards from the deck

  • Two-dimensional array: what is it?

    Show the answer

    A grid of values organised in rows and columns, where each cell is identified by two indices.

    In Python, it is a list of lists: m[i] is row i, and m[i][j] is the cell at row i and column j.

  • What does this program print?

    ```python
    m = [[1, 2, 3], [4, 5, 6]]
    print(m[1][2])
    `

    • 6
    • 3
    • 5
    • 8
    Show the answer

    6

    m[1] is the row [4, 5, 6], and its cell at index 2 is 6. 3 would be m[0][2], and 5 would be m[1][1].

  • In m[i][j], i is the … index and j is the … index.

    Show the answer

    In m[i][j], i is the row index and j is the column index.

    Read left to right: first the row m[i], then cell j of that row. Swapping the two gives another cell, or an IndexError on a non-square grid.

  • Row-by-row traversal: what is it?

    Show the answer

    A visiting order that finishes a whole row before moving to the next: the outer loop picks the row, the inner one goes through the columns.

    Swapping the two loops gives the column-by-column traversal. In C, a grid is stored in memory row after row: the row-by-row traversal is therefore the fastest.