2D arrays (grids)

Computer Science · Data structures

Question 1 of 10

0

    grid = [ [6, 3, 4, 2], [8, 7, 8, 1], [7, 9, 9, 8] ] Indices start at 0: grid[row][column]. What is the value of grid[0][0]?

    Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.

    How to type your answer
    • Fractions: 3/4. Mixed numbers: 1 1/2.
    • Decimals with a point or a comma: 0.75 or 0,75.
    • Negative numbers start with a minus: -3/4.
    • Percentages need the % sign: 75%.

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    2D arrays (grids) explained

    A two-dimensional array stores values in rows and columns, like a grid or a table. Each value is found with two indices, the row first and the column second. Both indices count from 0, so the first row is row 0 and the first column is column 0.

    Write the element in row r and column c as grid[r][c]. The outer list (or array) holds the rows, and each row is an inner list (or array). The number of rows is the length of the outer list, and the number of columns is the length of any one row. Python, Java and JavaScript all use this grid[r][c] form.

    Process a grid with nested loops, where the outer loop runs over the rows and the inner loop runs over the columns within each row. To sum a row, keep the row index fixed and vary the column index. To sum a column, keep the column index fixed and vary the row index. In an n by n grid, the main diagonal uses grid[i][i], and the other diagonal uses grid[i][n - 1 - i].

    Caveat: assigning one row to another variable does not copy its values. Both names refer to the same row, so changing one changes the grid.

    Worked example

    Here is a 3 by 3 grid:

    grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    

    What is the sum of the main diagonal?

    1. The main diagonal uses grid[0][0], grid[1][1] and grid[2][2].
    2. These hold 1, 5 and 9.
    3. Sum = 1 + 5 + 9 = 15.

    What you will practise

    New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.

    Example questions

    • Easy

      grid = [ [3, 1, 3, 6], [6, 3, 8, 5], [9, 2, 8, 9], [2, 8, 1, 5] ] Indices start at 0: grid[row][column]. What is the value of grid[0][2]?

    • Medium

      grid = [ [1, 1, 4], [6, 9, 5], [5, 6, 7], [4, 2, 3] ] Indices start at 0: grid[row][column]. What is the sum of all the values in row 1?

    • Hard

      grid = [ [9, 4, 3, 7], [2, 4, 5, 5], [3, 1, 4, 2], [6, 5, 3, 1] ] Indices start at 0: grid[row][column]. What is the sum of grid[i][i] for i = 0 to 3 (the main diagonal)?