Unit 4 • Lecture 2
A 2D Array is essentially an "Array of Arrays". While we visualize it as a table with rows and columns, the computer still sees it as one long, continuous strip of memory.
In C, 2D arrays use Row-Major Order. This means the entire first row is stored, followed immediately by the second row.
Accessing memory sequentially is faster due to CPU caching. Traversing a matrix row-by-row is usually faster than column-by-column because it follows the linear memory layout.
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};1. **int**: The type of data stored in every cell (integer).
2. **matrix**: The name of the 2D array.
3. **[2]**: The number of ROWS.
4. **[3]**: The number of COLUMNS.
5. **Initialization**: We use nested braces {}.
• The first inner brace {1, 2, 3} fills Row 0.
• The second inner brace {4, 5, 6} fills Row 1.
for(int i=0; i<2; i++) {
for(int j=0; j<3; j++) {
printf("%d ", matrix[i][j]);
}
}1. **Outer Loop (i)**: Controls the ROWS. It runs 2 times (0 to 1).
2. **Inner Loop (j)**: Controls the COLUMNS. For *every* row, this loop runs 3 times (0 to 2).
3. **mat[i][j]**: Accesses the specific cell.
• When i=0, j goes 0,1,2 -> accessing Row 0.
• When i=1, j goes 0,1,2 -> accessing Row 1.
*Valid: Row size can be inferred, but column size is mandatory.
*Invalid: Compiler must know the column count (stride) to calculate memory jumps.
Watch how the inner loop completes a full cycle for every single step of the outer loop.
Verify the Row-Major Formula: Addr(A[i][j]) = Base + (i × N + j) × Size
Matrix addition happens cell-by-cell. Sum[i][j] = A[i][j] + B[i][j].
Addition, Multiplication, Determinants.
Images are just 2D arrays of pixels (RGB values).
Chess, Tic-Tac-Toe, and Sudoku grids.
Storing spreadsheets or database records.
Solving complex pathfinding problems.
Adjacency matrices to represent network connections.