Attention!
This wiki is only valid for the older IB Computer Science Curriculum (last exam 2026).
Please do not use this wiki for IB computer science for the new curriculum (first exam 2027).
This wiki will sunset on June 1 2026. This FAQ is now an unofficial digital knowledgebase for the new IB CS course. Please email me with any questions: [email protected]
Two-dimensional arrays
πΎ What is a Two-Dimensional Array?[edit]
A two-dimensional array is a contiguous block of memory that stores elements in rows and columns. It is essentially an array of arrays β each element in the outer array is itself an inner array.
In most high-level programming languages (such as Python or Java), a 2D array is indexed using two indices:
- The first index represents the row
- The second index represents the column
β Accessing Elements[edit]
To access an element in a 2D array, use the following syntax:
array[row][column]
Example (Python):
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
To access the number 6, you would write:
matrix[1][2]
Explanation:
matrix[1]returns the second row:[4, 5, 6]matrix[1][2]returns the third element in that row:6
π Updating Elements[edit]
To update an element in a 2D array, use the same syntax on the left-hand side of an assignment:
matrix[2][0] = 99
This updates the first element of the third row to 99. The new array is:
[
[1, 2, 3],
[4, 5, 6],
[99, 8, 9]
]
π Traversing a 2D Array[edit]
To process every element in a 2D array, use nested loops:
for row in range(len(matrix)):
for col in range(len(matrix[row])):
print(matrix[row][col])
This prints every element in row-major order (left-to-right, top-to-bottom).
π§ Common Mistakes[edit]
| Mistake | Explanation |
|---|---|
Mixing up row and column |
Accessing matrix[column][row] by mistake gives incorrect results or errors.
|
| Using invalid indices | Accessing matrix[3][0] in a 3Γ3 matrix (0-indexed) will raise an IndexError.
|
| Assuming all rows are the same length | In Python, inner arrays can be jagged. Always use len(matrix[row]) instead of assuming a fixed length.
|
π§ͺ Practice Task[edit]
Given the following array:
grades = [
["Alice", 85],
["Bob", 78],
["Clara", 92]
]
- What does
grades[2][0]return? - Change Bob's grade to
80. - Loop through the array and print each student name and grade.
A video[edit]
This video has some references to Java, but it should help you understand the very basics of 2d arraysΒ : https://www.youtube.com/watch?v=nySZfYSVspo
Standards[edit]
- Construct algorithms using pre- defined sub-programmes, one- dimensional arrays and/or collections.