Logo

2D Arrays & Matrices

Unit 4 • Lecture 2

The Grid Paradigm

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.

Grid vs. Linear Memory

In C, 2D arrays use Row-Major Order. This means the entire first row is stored, followed immediately by the second row.

Row-Major Mapping

Logical View (2D)
1
2
3
4
5
6
7
8
9
Hover to trace memory
Physical Memory (1D)
10
21
32
43
54
65
76
87
98
Index = (Row × Cols) + Col

Why Row-Major Matters?

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.

Syntax & Processing

Declaration

c
int matrix[2][3] = {
  {1, 2, 3}, 
  {4, 5, 6}
};

Traversal Pattern

c
for(int i=0; i<2; i++) {
  for(int j=0; j<3; j++) {
    printf("%d ", matrix[i][j]);
  }
}

Initialization Patterns

int mat[2][2] = {{1,2},{3,4}};
int mat[2][2] = {1,2,3,4};
int mat[][2] = {1,2,3,4};

*Valid: Row size can be inferred, but column size is mandatory.

int mat[2][] = {1,2,3,4};
int mat[][] = {1,2,3,4};

*Invalid: Compiler must know the column count (stride) to calculate memory jumps.

Nested Loop Simulator

Watch how the inner loop completes a full cycle for every single step of the outer loop.

Nested Loop Traversal

// Printing Matrix
for(int i=0; i<2; i++) { // Outer (Rows)
for(int j=0; j<3; j++) { // Inner (Cols)
printf("%d ", mat[i][j]);
}
}
Current i: 0
Current j: -
1[0][0]
2[0][1]
3[0][2]
4[1][0]
5[1][1]
6[1][2]

Address Calculation

Address Calculator

Verify the Row-Major Formula: Addr(A[i][j]) = Base + (i × N + j) × Size

Linear Index Calculation
1 (row) × 3 (cols) + 2 (col) = 5
Final Address
2000 + (5 × 4) = 2020

Interactive Matrix Addition

Matrix Addition Lab

Matrix addition happens cell-by-cell. Sum[i][j] = A[i][j] + B[i][j].

Matrix A
Matrix B
Result
6
8
10
12

Applications

Matrix Math

Addition, Multiplication, Determinants.

Image Processing

Images are just 2D arrays of pixels (RGB values).

Game Boards

Chess, Tic-Tac-Toe, and Sudoku grids.

Tabular Data

Storing spreadsheets or database records.

Dynamic Programming

Solving complex pathfinding problems.

Graphs

Adjacency matrices to represent network connections.