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.
ExampleTwo-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.