← Back to C Course Foundations
Two-Dimensional Numeric Array (C)¶
Learning Objectives¶
- Declare and initialize 2D numeric arrays.
- Perform addition, subtraction, multiplication, and transpose.
- Compute element addresses in row-major and column-major order.
Concept¶
A 2D array stores values in rows and columns. In C, memory is stored in row-major order by default.
Algorithm (Matrix Addition)¶
- Read matrix dimensions
randc. - Input matrix
A[r][c]andB[r][c]. - For each cell
(i, j), computeC[i][j] = A[i][j] + B[i][j]. - Print matrix
C.
C Example¶
#include <stdio.h>
int main(void) {
int r = 2, c = 3;
int A[2][3] = {{1, 2, 3}, {4, 5, 6}};
int B[2][3] = {{6, 5, 4}, {3, 2, 1}};
int C[2][3];
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
printf("Result (A + B):\n");
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
printf("%d ", C[i][j]);
}
printf("\n");
}
int i = 1, j = 2;
int cols = 3;
int base = 1000; // assumed base address
int size = sizeof(int);
int row_major_addr = base + ((i * cols + j) * size);
printf("Address of A[1][2] (row-major formula): %d\n", row_major_addr);
return 0;
}
Dry Run (Addition)¶
A[0][1] = 2,B[0][1] = 5->C[0][1] = 7A[1][2] = 6,B[1][2] = 1->C[1][2] = 7
Output matrix:
Common Mistakes¶
- Mismatched matrix dimensions for operations.
- Wrong loop bounds (
i < r,j < c). - Confusing row-major and column-major formulas.
Practice¶
- Write matrix subtraction.
- Write matrix transpose.
- Implement 2x2 matrix multiplication.