DoAssignment study guide

A3.5 · Two-Dimensional Arrays and Nested Loops

Learn to process a two-dimensional array through clear examples and targeted practice.

Ontario Grade 12 Computer Science

Programming Concepts and Skills

ICS4U A3.5 | Working with rows and columns

A two-dimensional array organizes values into rows and columns. Processing one can mean displaying its values, adding them, counting values that meet a condition, or changing one position. This lesson uses Python 3 lists of lists as a representation. It assumes you can work with variables, lists, loops, and conditional statements from ICS3U. Each element is located with two indexes: first the row, then the column within that row. The examples show expected results by tracing the supplied inputs; the code is presented for study and is not claimed to have been run.

What you will learn

  • Locate an element using its row and column indexes.
  • Use nested loops to process every element in a rectangular two-dimensional array.
  • Trace a total, a conditional count, and a single-element update to determine expected results.

1. Review: two indexes locate a value

A one-dimensional list uses one index to select a position. A two-dimensional array adds another level of organization: each row contains a sequence of values, and an element is selected by giving its row and its position in that row. In Python, a common representation is a list of lists: the outer list contains rows, and each inner list contains the values in one row.
Python indexes begin at zero. In a grid named grid, grid[1][2] selects row 1, then column 2 in that row. In ordinary counting, this is the second row and the third value within it. Keep the order straight: the first index is the row, and the second is the column.
These examples use rectangular grids, where each row has the same number of values. The number of rows is len(grid); the number of columns in a row is len(grid[row]). For example, a grid with three rows has row indexes 0, 1, and 2. A row with four values has column indexes 0, 1, 2, and 3.
  • A Python list of lists is a common way to represent a two-dimensional array.
  • Read grid[row][column]: first choose the row, then a value in that row.
  • Indexes start at zero; the last valid index is one less than the number of positions.

2. Traverse rows and process values

To visit every element, use nested loops. The outer loop chooses a row. The inner loop visits each column in that row before the outer loop moves to the next row. This produces a predictable traversal: across the first row, then across the next row, and so on.
Place the operation on the current element inside the inner loop, where both indexes identify it. For a total, add grid[row][col] to a running total. For a count, test the current value and increase the count only when it meets the condition. Initialize the total or count before the loops begin so progress is not lost during traversal.
A trace records the current row, column, value, and any running result. If a traversal encounters 3 and then 1, a total initialized at 0 changes first to 3 and then to 4. Tracing can reveal a skipped position, a repeated position, or indexes used in the wrong order.
  • The outer loop selects rows; the inner loop visits columns in the selected row.
  • Initialize a running result before the loops and update it as values are processed.
  • Trace values in row order to check that the requested positions are handled.

3. Apply a condition or update a position

A condition can determine which elements contribute to a result. Put the condition inside the inner loop when it must be checked for every element. For example, a count of scores at least 6 increases only when the current score satisfies that comparison.
Some tasks ask you to change just one position. An assignment such as grid[0][1] = 'X' selects row 0, column 1, and replaces that element. Check that both indexes are valid. Updating one element does not replace an entire row or the whole grid.
Before processing, state the input, operation, preconditions, and expected output. A total needs a running total; a conditional count needs a running count and a condition; an update needs the requested row and column. Then follow the traversal or access steps and check that the result answers the task.
  • Check a condition separately for each relevant element.
  • Use both indexes to access or change one element.
  • State the expected output before tracing so you know what result to verify.

4. A plan for tracing and checking

Start by inspecting the grid and identifying its rows and columns. Next, choose the requested operation: traverse all elements for a total or count, or access a specified position for a single update. Set any running result before traversal. Follow the loops in order and record changes to that result.
For practice, consider [[4, 1], [6, 3]]. Trace a total in traversal order, then count values greater than 3, and identify the value at row 1, column 0. A total trace adds 4, then 1, then 6, then 3. For the count, check each value against the condition. The indexed value is the first value in the second row.
Finish with a task-specific check. For a total, account for each required value once. For a count, check each comparison and each increase. For an update, confirm the intended position changed and other positions stayed the same. These are checks of expected results derived from the input.
  • Identify the input, operation, preconditions, and output before coding.
  • Complete the inner loop before moving to the next row.
  • Compare the traced result with the task and the original grid.

Worked example

Add all values in a grid

Input: a rectangular grid of numbers. Find and display the sum of every value in [[3, 1, 4], [2, 5, 0]]. Preconditions: the grid has at least one row, contains numbers, and all rows have the same number of columns. Trace the traversal and determine the expected output.
Grid values by row and column
row, column314250

Each cell is labelled with its row and column indexes. The traversal completes row 0 before row 1.

Python 3

grid = [[3, 1, 4], [2, 5, 0]]
total = 0
for row in range(len(grid)):
    for col in range(len(grid[row])):
        total += grid[row][col]
print(total)
  1. Initialize
    Set total to zero before visiting any values. The input is the supplied grid; the requested output is the sum of its elements.
  2. Traverse and add
    The nested loops visit the values in this order: 3, 1, 4, 2, 5, 0. The running total becomes 3, 4, 8, 10, 15, and 15. Each position contributes once.
  3. State the result
    The first row contributes 8 and the second row contributes 7, so the expected displayed output is 15.
    8+7=158 + 7 = 15
Answer: The expected total is 15.
Check: All six positions were visited once. Including the final zero does not change the total.

Worked example

Count values meeting a condition

Input: a grid of whole-number scores. Count the values that are at least 6 in [[6, 2, 9], [5, 7, 4]]. Preconditions: the grid has at least one row and its elements are whole numbers. Trace each comparison and determine the expected output.
Scores by row and column
row, column6 ✓29 ✓57 ✓4

A check mark identifies a value that is at least 6. Cell labels give row and column indexes.

Python 3

scores = [[6, 2, 9], [5, 7, 4]]
count = 0
for row in range(len(scores)):
    for col in range(len(scores[row])):
        if scores[row][col] >= 6:
            count += 1
print(count)
  1. Set the starting count
    Start at zero because no values have been checked. The count changes only when the current value is at least 6.
  2. Check each value
    The traversal order is 6, 2, 9, 5, 7, 4. The values 6, 9, and 7 meet the condition. The other three comparisons do not increase the count.
  3. State the result
    The count increases three times, so the expected displayed output is 3.
    33
Answer: The expected count is 3.
Check: Exactly three of the six values are at least 6.

Worked example

Update one specified element

Input: a grid of labels and a requested position. In [['A', 'B'], ['C', 'D']], change the value at row 1, column 0 to 'X'. Preconditions: row 1 and column 0 are valid indexes. Determine the expected grid after the assignment.
Grid after the specified update
row, columnABX (was C)D

The value at row 1, column 0 changes from C to X; the other positions are unchanged.

Python 3

grid = [['A', 'B'], ['C', 'D']]
grid[1][0] = 'X'
print(grid)
  1. Select the row
    Because indexes start at zero, row 1 is the second inner list: ['C', 'D'].
  2. Select and replace the element
    Within row 1, column 0 selects 'C'. Assigning 'X' to that position changes this element only; the other three values remain unchanged.
  3. Read the expected grid
    After the assignment, the expected grid is [['A', 'B'], ['X', 'D']].
Answer: The resulting grid is [['A', 'B'], ['X', 'D']].
Check: The value at row 1, column 0 changes from C to X. The values at the other indexes stay the same.

Common mistakes and how to avoid them

Treating the first index as the column and the second as the row.
Correction: Read grid[row][column]: the first index selects a row, and the second selects a value within that row.
Using the number of columns as the outer loop limit.
Correction: The outer loop visits rows. The inner loop visits columns in the current row.
Resetting a total or count during traversal.
Correction: Initialize the running result before the loops so earlier progress is preserved.
Increasing a conditional count for every value.
Correction: Place the increment inside the condition so only qualifying values change the count.

Lesson summary

  • A two-dimensional array organizes values in rows and columns; each element has a row index and a column index.
  • Nested loops process a grid row by row, with the inner loop completing one row before the outer loop advances.
  • Initialize totals and counts before traversal, and update them according to the requested task.
  • Use both indexes to access or change one element.
  • Trace the values and result to check the expected output.

Check your understanding

Question 1

In a Python grid, what does grid[2][1] identify?
  1. The value in row 2, column 1
  2. The value in row 1, column 2
  3. The third value in the first row
  4. The entire second row
Show answer and explanation
The value in row 2, column 1
The first index selects row 2; the second selects column 1 within that row.

Question 2

A grid contains [[2, 3], [4, 1]]. What total results from adding every element once?
  1. 8
  2. 9
  3. 10
  4. 11
Show answer and explanation
10
The first row totals 5 and the second row totals 5, giving a total of 10.

Question 3

Which loop arrangement visits every element in a rectangular grid?
  1. An outer loop over rows and an inner loop over columns in the current row
  2. An outer loop over columns and an inner loop over only the first row
  3. A single loop that uses only the row index
  4. An inner loop that resets the grid after each row
Show answer and explanation
An outer loop over rows and an inner loop over columns in the current row
For each row selected by the outer loop, the inner loop visits every column in that row.

Key terms

Two-dimensional array
A collection of values organized by rows and columns; in Python it is commonly represented as a list of lists.
Row index
The index used to select a row in a grid.
Column index
The index used to select an element within a selected row.
Traversal
A planned sequence for visiting elements in a collection.
Running total
A variable that stores a sum as values are processed.

Continue through ICS4U

View the complete ICS4U Ontario Grade 12 Computer Science curriculum and lessons

About this lesson and its review

Published by DoAssignment. This reviewed lesson follows Ontario Grade 12 Computer Science (ICS4U), expectation A3.5. It is a study resource, not an official curriculum publication.

Before publication, content is checked for structure, mathematical or chemical notation, calculations, course boundaries, and readability. Errors can still occur, so corrections are welcomed.

Official curriculum reference

Report a correction or ask a question