A one-dimensional array stores an ordered sequence of elements accessed using one index. A two-dimensional array organizes elements into rows and columns, so each element requires two indices.
How arrays store data
An array usually contains elements of the same data type and has a fixed size after creation. An index identifies an element's position and may begin at 0 or 1.
For scores = [72, 85, 91, 68], scores[2] is 91 with zero-based indexing but 85 with one-based indexing. Follow the question's convention.
A 2D array can represent tabular data:
marks = [[72, 85, 91],
[68, 74, 88]]
With zero-based indexing, marks[1][2] accesses row 1, column 2, giving 88.
| Feature | 1D array | 2D array |
|---|---|---|
| Structure | Linear list | Rows and columns |
| Element access | One index: array[i] | Two indices: array[row][column] |
| Typical use | Names, temperatures, scores | Grids, game boards, tables |
| Traversal | One loop | Nested loops |
Traversing and updating arrays
A 1D array is normally processed with one loop:
for each score in scores
output score
end for
A 2D array requires nested iteration: the outer loop traverses rows and the inner loop traverses columns. Assignment updates a value, such as scores[0] = 80, but does not resize the array.
A common misconception is that a 2D array is simply two separate arrays. It is one data structure whose elements are located using a pair of indices, often implemented as an array of arrays.
Exam technique
For IB Computer Science B2.2, trace indices carefully, state the indexing convention, and distinguish access, update, and traversal. When writing pseudocode for a 2D array, show correctly bounded nested loops and use the row and column indices in the correct order.