Two-Dimensional Arrays (2D) & Matrix Operations
Unit 3: Arrays, Pointers & String Manipulation • Problem Solving Using C
👨🏫 Professor's Mental Model: The Spreadsheet Grid & Apartment Floor-Room System
2D Array ek Excel spreadsheet ya multi-floor apartment building jaisa hai! Pehla index floor number (Row) batata hai aur doosra index flat number (Column). Lekin computer ki RAM 2D nahi hoti, wo ek seedhi 1D line hoti hai! Isliye C Row-Major Order use karta hai: pehle floor 0 ke saare flats RAM me aate hain, fir floor 1 ke flats, fir floor 2 ke flats!
Academic Lecture Notes & Solved Study Pages
Unit 3 • Core Concepts, Step-by-Step Proofs & Notebook Solutions
1. 2D Array Declaration & Memory Architecture
`int mat[2][3] = {{1, 2, 3}, {4, 5, 6}};`
2. Row-Major Order vs Column-Major Order
Elements are stored row by row. Row 0 elements are laid down first, then Row 1, etc.
Memory Address Formula:
$\text{Address}(A[i][j]) = \text{Base Address} + (i \times \text{COLS} + j) \times \text{sizeof(element)}$
Elements are stored column by column.
Memory Address Formula:
$\text{Address}(A[i][j]) = \text{Base Address} + (j \times \text{ROWS} + i) \times \text{sizeof(element)}$
3. Matrix Multiplication Algorithm & Conditions
Two matrices A ($R_1 \times C_1$) and B ($R_2 \times C_2$) can be multiplied if and only if $C_1 == R_2$ (Columns of Matrix A equal Rows of Matrix B).
| Element | Row (i) | Column (j) | Linear Index (i*COLS + j) | Physical Address (Base = 0x5000) |
|---|---|---|---|---|
| mat[0][0] | 0 | 0 | 0*3 + 0 = 0 | 0x5000 |
| mat[0][1] | 0 | 1 | 0*3 + 1 = 1 | 0x5004 |
| mat[0][2] | 0 | 2 | 0*3 + 2 = 2 | 0x5008 |
| mat[1][0] | 1 | 0 | 1*3 + 0 = 3 | 0x500C |
| mat[1][1] | 1 | 1 | 1*3 + 1 = 4 | 0x5010 |
| mat[1][2] | 1 | 2 | 1*3 + 2 = 5 | 0x5014 |
Interactive Tested Code Example
#include <stdio.h>
#define R1 2
#define C1 2
#define R2 2
#define C2 2
int main(void) {
int A[R1][C1] = {{1, 2}, {3, 4}};
int B[R2][C2] = {{5, 6}, {7, 8}};
int C[R1][C2] = {0};
// Matrix Multiplication Algorithm
for (int i = 0; i < R1; i++) {
for (int j = 0; j < C2; j++) {
for (int k = 0; k < C1; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
printf("=== MATRIX MULTIPLICATION RESULT (2x2) ===\n");
for (int i = 0; i < R1; i++) {
printf("| ");
for (int j = 0; j < C2; j++) {
printf("%-4d ", C[i][j]);
}
printf("|\n");
}
return 0;
}🎯 University Exam Scoring Blueprint
- In university exams, always derive the Row-Major formula: Address(A[i][j]) = Base + (i * COLS + j) * size.
- Remember that when passing a 2D array to a function, the column size MUST be specified in formal parameters: void func(int arr[][3]).
- State the matrix multiplication condition: Columns of First = Rows of Second.