Two-Dimensional Arrays
Understanding Two-Dimensional Arrays
Two-dimensional array
A data structure that organizes data in a grid-like format. It consists of rows and columns, allowing you to store and access data using two indices.
Formally speaking, a two-dimensional array is an array of arrays.
Two-dimensional array in Python:
arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]Or in more readable form:
arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]- Think of a two-dimensional array as a spreadsheet.
- Each cell in the spreadsheet can hold a value, and you can access any cell by specifying its row and column.
Two-dimensional arrays are useful for:
- Matrices: Used in mathematical computations and simulations.
- Grids and Maps: Ideal for representing game boards, pixel grids, and geographical maps.
- Data Tables: Useful for storing tabular data, such as spreadsheets or databases.
- Image Processing: Useful for representing pixels in digital images.
- Consider a scenario where you need to store exam scores for five students, each taking three exams.
- A two-dimensional array is an ideal choice for this task.
- Possible structure:
- Rows represent students, columns represent test scores
- Scores[0][0] refers to the first exam score of the first student, which is 98.
- Scores[2][1] refers to the second exam score of the third student, which is 63.
| 98 | 97 | 59 |
|---|---|---|
| 75 | 56 | 86 |
| 100 | 63 | 67 |
| 45 | 90 | 80 |
| 76 | 23 | 54 |
Key Characteristics of Two-Dimensional Arrays
- Structure:
- Each element in the main array is a sub-array representing a row.
- Indexing:
- Two indices are used to access elements: first for the row and second for the column.
- Indices typically start at 0, so the first element is accessed as array[0][0].
- Uniform Data Type:
- All elements in a two-dimensional array must be of the same data type, such as integers, strings, or objects.
- Fixed Size:
- The size of a two-dimensional array is defined at the time of creation and cannot be changed.
- In strongly typed programming languages, you must specify the number of rows and columns when declaring the array.
- Memory Layout:
- Elements are stored in contiguous memory locations, which allows for efficient access and manipulation.
Try to experiment with indexing:
arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(arr[0]) # Output 0th row
print(arr[1][1])When working with two-dimensional arrays, always remember that the first index refers to the row, and the second index refers to the column.
- Accessing and modifying elements in a two-dimensional array is straightforward.
- You use the row and column indices to specify the exact location of the element.
Algorithms with Two-Dimensional Arrays
When working with two-dimensional arrays, always remember that the first index refers to the row, and the second index refers to the column.
Iterating Over a Two-Dimensional Array
Iterating over a two-dimensional array typically involves nested loops: one for the rows and another for the columns.
arr =[ # 2d array of strings
["A1", "A2", "A3", "A4"],
["B1", "B2", "B3", "B4"]
]
for y in range(2):# outer loop
for x in range(4): # inner loop
print(f"y = {y}, x = {x}, value = {arr[y][x]}")With iteration of a two-dimensional array, you can construct different algorithms such as searching or calculating the sum of rows/columns.
Transposing a Matrix
- Transposing a matrix involves swapping rows and columns.
- For a matrix A, the transpose B is defined as B[j][i] = A[i][j].
- The transpose of a matrix changes its dimensions.
- If A is $m \times n$, then B will be $n \times m$.
// ARR is original NxM array (N and M given)
// NEWARR is new MxN array filled with 0
loop Y from 0 to N-1
loop X from 0 to M-1
NEWARR[X][Y] = ARR[Y][X]
end loop
end looparr =[ # 2d array of strings
["A1", "A2", "A3", "A4"],
["B1", "B2", "B3", "B4"]
]
rows = len(arr)
cols = len(arr[0])
result = [[0 for y in range(rows)] for x in range(cols)] # Python list comprehension, fill 4x2 array with 0
for y in range(rows):
for x in range(cols):
result[x][y] = arr[y][x]
for row in result: # Print every sub-array
print(row)Tips for working with two-dimensional arrays:
- Visualise the structure: Draw the array as a grid to understand the relationships between elements better.
- Use descriptive variable names: Use names like row and col for loop indices to improve code readability.
- Be mindful of boundaries: Always ensure your loops stay within the array's defined dimensions to avoid out-of-bounds errors.
- Can you explain how a two-dimensional array differs from a one-dimensional array?
- Try to write pseudocode for:
- calculating the sum
- of all its elements
- of elements by row
- of elements by columns
- calculating the average of all elements
- finding the maximum
- calculating the sum
- How would you modify the search algorithm to return the coordinates of the found element?
- What are some real-world scenarios where two-dimensional arrays are particularly useful?