2D Arrays — The Concept
A 2D array is an array of arrays — imagine it as a grid or table with rows and columns. Each element is accessed using two indices: [row][column], both zero-indexed.
A 3×3 grid looks like this — indices run from 0:
| Index | Col 0 | Col 1 | Col 2 |
| Row 0 | grid[0][0] | grid[0][1] | grid[0][2] |
| Row 1 | grid[1][0] | grid[1][1] | grid[1][2] |
| Row 2 | grid[2][0] | grid[2][1] | grid[2][2] |
Accessing and Updating Elements
// Storing a 3×3 noughts-and-crosses grid
board[0][0] ← "X"
board[0][1] ← "O"
board[0][2] ← "X"
board[1][0] ← "O"
board[1][1] ← "X"
board[1][2] ← "O"
OUTPUT board[1][1] // "X" — middle cell
// Update top-right corner
board[0][2] ← "O"
Traversing with Nested FOR Loops
Use nested FOR loops to visit every element — the outer loop iterates over rows, the inner loop over columns.
// Output all elements of a 4-row, 3-column grid
FOR row ← 0 TO 3
FOR col ← 0 TO 2
OUTPUT grid[row][col]
ENDFOR
ENDFOR
Worked Example — Class Marks
Storing marks for 3 students across 4 subjects (rows = students, cols = subjects):
marks[0][0] ← 78 // Student 1, Subject 1
marks[0][1] ← 85 // Student 1, Subject 2
marks[1][0] ← 90 // Student 2, Subject 1
marks[1][1] ← 72 // Student 2, Subject 2
// Calculate total for student 0 across 4 subjects
total ← 0
FOR col ← 0 TO 3
total ← total + marks[0][col]
ENDFOR
OUTPUT "Total: " + str(total)
Searching a 2D Array
// Find the value 100 in a 4×4 grid
found ← False
FOR row ← 0 TO 3
FOR col ← 0 TO 3
IF grid[row][col] == 100 THEN
found ← True
OUTPUT "Found at row " + str(row) + ", col " + str(col)
ENDIF
ENDFOR
ENDFOR
Use Cases for 2D Arrays
| Scenario | Rows represent | Columns represent |
| Class marks | Students | Subject marks |
| Game board | Row on board | Column on board |
| Image (pixel map) | Pixel row | Pixel column |
| Timetable | Day of week | Period/lesson slot |
Exam tip: Always write the index as [row][column]. If asked "what is stored at grid[2][1]?", remember row 2 is the third row and column 1 is the second column — both are zero-indexed.
⚠️ Common Mistakes
- Swapping row and column — grid[row][col] not grid[col][row]
- Forgetting zero-indexing — a 3×3 grid has indices 0,1,2 not 1,2,3
- Only one ENDFOR in a nested loop — each FOR needs its own ENDFOR
- Going off the end of the array — a 4-row grid goes TO 3, not TO 4