Resources | Subject Notes | Computer Science
Arrays are fundamental data structures used to store collections of elements of the same data type. Choosing the right type of array (1D or 2D) is crucial for efficiency and code clarity. This section explores when to use each type.
A 1D array is a linear collection of elements, accessed using a single index. It's suitable for representing sequences or lists where elements have a direct, ordered relationship.
Example (Python):
my_array = [10, 20, 30, 40, 50]
print(my_array[0]) # Output: 10
A 2D array is an array of arrays, essentially representing a table or a grid. It's used to organize data into rows and columns.
Example (Python):
my_array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(my_array[1][2]) # Output: 6
The choice between a 1D and a 2D array depends on how the data is structured and how it will be accessed.
Feature | 1D Array | 2D Array |
---|---|---|
Data Structure | Linear sequence | Table/Grid |
Indexing | Single index | Two indices (row, column) |
Memory Allocation | Contiguous memory | Contiguous memory |
Accessing Elements | Efficient for sequential access | Efficient for accessing elements within a row or column |
Use Cases | Lists, sequences, stacks, queues | Matrices, spreadsheets, grids, images |
In mathematics, a 2D array is often used to represent a matrix. A matrix is a rectangular array of numbers. The elements of a matrix are denoted by $a_{ij}$, where $i$ represents the row number and $j$ represents the column number.
For example, a matrix $A$ can be represented as:
$$ A = \begin{bmatrix} a_{11} & a_{12} \\ a_{21} & a_{22} \end{bmatrix} $$When selecting an array, consider the following: