- How to pass 2D arrays to functions ā and why the column dimension must be fixed
- How to write nested loops over rows and columns
- Why matrix addition requires matching dimensions
- How to read and print matrices in a grid layout
- How this elementwise-addition pattern generalizes to subtraction and other matrix operations
What matrix addition means
A matrix is a rectangular grid of numbers, organised in rows and columns. An m Ć n matrix has m rows and n columns. For example, a 3 Ć 3 matrix has 9 entries. In C, we represent a matrix as a 2D array: int M[3][3] ā the first index is the row, the second is the column.
Matrix addition is elementwise: if A and B are both m Ć n matrices, their sum C = A + B is an m Ć n matrix where each entry C[i][j] = A[i][j] + B[i][j]. The (0, 0) entry of C is the sum of the (0, 0) entries of A and B, the (0, 1) entry is the sum of the (0, 1) entries, and so on. There's no cross-talk between positions ā each cell adds independently.
Two conditions must be satisfied. First, both matrices must have the same dimensions (same number of rows, same number of columns). You can't add a 3 Ć 3 matrix to a 2 Ć 4 matrix ā there's no meaningful way to pair up entries. Second, the result matrix must also have those dimensions ā it's the same shape as the inputs. These conditions are checked by the caller (in our program, by using the same dimensions for all three matrices), not by the function. The function's contract is "give me three same-shaped matrices, and I'll fill in the third with the sum."
This elementwise operation is the simplest matrix operation. Matrix multiplication is more involved (each entry is a dot product), and scalar multiplication is even simpler (multiply every entry by one number). Matrix addition is a good starting point because it's the easiest to visualize and the most mechanical to implement. Once you've got it, the other operations follow similar patterns, with different formulas.
š” In one line: for each row i and each column j, set result[i][j] = a[i][j] + b[i][j]. That's it ā a nested loop, one addition per cell.
Designing the addMatrices function
Matrix functions have a subtlety: the column dimension must be known at compile time for pointer arithmetic to work. Here are the key choices:
| Part | Choice | Why |
|---|---|---|
| Function name | addMatrices | Descriptive. Alternatives: matrixAdd, sumMatrices. |
| Parameters | int a[ROWS][COLS], int b[ROWS][COLS], int result[ROWS][COLS] | Three 2D arrays. The first two are inputs; the third is the output. ROWS and COLS are #defined constants. |
| Return type | void | The result goes into the third parameter. Nothing to return. |
| Column dimension | Must be specified | int a[][COLS] works, but int a[][] is illegal. C needs the inner stride for indexing. |
The prototype uses compile-time constants for the dimensions:
#define ROWS 3
#define COLS 3
void addMatrices(int a[ROWS][COLS], int b[ROWS][COLS], int result[ROWS][COLS]);
And the definition:
void addMatrices(int a[ROWS][COLS], int b[ROWS][COLS], int result[ROWS][COLS]) {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
result[i][j] = a[i][j] + b[i][j];
}
}
}
Six lines of logic. The outer loop goes over rows; the inner over columns. For each cell, we add the corresponding entries from a and b and store them in result. Every cell is visited exactly once, and every cell is set exactly once. Nothing is missed, nothing is done twice.
A note on the declaration. When you pass a 2D array to a function, the compiler needs to know the shape of the array to compute element offsets. Since a[i][j] is at memory location base + i*COLS*sizeof(int) + j*sizeof(int), the value of COLS must be known. That's why you must declare the parameter as int a[][COLS] or int (*a)[COLS] ā omitting the inner dimension is a compile error. The outer dimension (ROWS) is optional because it's not needed for indexing.
Here's a version that uses variable dimensions ā for matrices whose size isn't known at compile time:
void addMatricesVLA(int rows, int cols, int a[rows][cols], int b[rows][cols], int result[rows][cols]) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = a[i][j] + b[i][j];
}
}
}
This uses C99's variable-length array (VLA) feature. The dimensions are passed as parameters before the arrays, and the array declarations reference them. This works on compilers that support C99 or later (most modern ones do). The limitation is that VLAs can't be used in global or static contexts ā they're strictly local to the function. For most teaching and simple examples, the #define version is more portable; for flexible sizes, VLAs are the way.
šÆ Key idea: the inner dimension of a 2D array parameter must be a compile-time constant (or a VLA-bound parameter). This is because C needs the inner stride to compute row offsets. The outer dimension is optional ā it's not used for indexing.
Complete C Program
Program: read two 3Ć3 matrices, add them, print the result
#include <stdio.h>
#define ROWS 3
#define COLS 3
/* Function prototypes */
void readMatrix(int mat[ROWS][COLS], const char *name);
void printMatrix(const int mat[ROWS][COLS], const char *name);
void addMatrices(const int a[ROWS][COLS], const int b[ROWS][COLS], int result[ROWS][COLS]);
int main(void) {
int A[ROWS][COLS], B[ROWS][COLS], sum[ROWS][COLS];
readMatrix(A, "A");
readMatrix(B, "B");
addMatrices(A, B, sum);
printMatrix(A, "A");
printMatrix(B, "B");
printMatrix(sum, "A + B");
return 0;
}
void readMatrix(int mat[ROWS][COLS], const char *name) {
printf("Enter matrix %s (%d rows, %d columns):\n", name, ROWS, COLS);
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
if (scanf("%d", &mat[i][j]) != 1) {
printf("Invalid input.\n");
return;
}
}
}
}
void printMatrix(const int mat[ROWS][COLS], const char *name) {
printf("\nMatrix %s:\n", name);
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("%5d", mat[i][j]);
}
printf("\n");
}
}
void addMatrices(const int a[ROWS][COLS], const int b[ROWS][COLS], int result[ROWS][COLS]) {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
result[i][j] = a[i][j] + b[i][j];
}
}
}
And a version that uses variable-length arrays so the dimensions can be chosen at runtime:
Variant: variable-size matrices (C99 VLAs)
#include <stdio.h>
void addMatrices(int rows, int cols, int a[rows][cols], int b[rows][cols], int result[rows][cols]) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = a[i][j] + b[i][j];
}
}
}
int main(void) {
int rows, cols;
printf("Enter rows and cols: ");
if (scanf("%d %d", &rows, &cols) != 2 || rows <= 0 || cols <= 0) return 1;
int A[rows][cols], B[rows][cols], sum[rows][cols];
printf("Enter matrix A:\n");
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
scanf("%d", &A[i][j]);
printf("Enter matrix B:\n");
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
scanf("%d", &B[i][j]);
addMatrices(rows, cols, A, B, sum);
printf("Sum:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%5d", sum[i][j]);
}
printf("\n");
}
return 0;
}
This version handles any matrix size the user requests. The VLA syntax int A[rows][cols] on the stack is valid in C99 and later (and is a common extension in older compilers). For very large matrices (say, 1000Ć1000), you'd want to allocate on the heap instead ā VLAs of that size could overflow the stack. For teaching and small examples, VLAs are fine.
And a version that computes matrix subtraction in parallel ā showing the symmetry:
Variant: subtraction and scalar multiplication together
#include <stdio.h>
#define N 3
void subtractMatrices(int a[N][N], int b[N][N], int result[N][N]) {
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
result[i][j] = a[i][j] - b[i][j];
}
void scalarMultiply(int a[N][N], int k, int result[N][N]) {
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
result[i][j] = k * a[i][j];
}
int main(void) {
int A[N][N] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int B[N][N] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int diff[N][N], scalar[N][N];
subtractMatrices(A, B, diff);
scalarMultiply(A, 3, scalar);
printf("A - B:\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) printf("%4d", diff[i][j]);
printf("\n");
}
printf("\n3 * A:\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) printf("%4d", scalar[i][j]);
printf("\n");
}
return 0;
}
The two functions have the same nested-loop structure as matrix addition ā only the per-element operation differs (- vs + vs *). This is the fundamental pattern: iterate over all cells, compute something from the inputs, store in the output. Matrix multiplication has the same outer structure, but the inner computation is a dot product instead of a single arithmetic operation ā that's the twist.
Program Output
A typical run with two simple matrices:
Enter matrix A (3 rows, 3 columns):
1 2 3
4 5 6
7 8 9
Enter matrix B (3 rows, 3 columns):
9 8 7
6 5 4
3 2 1
Matrix A:
1 2 3
4 5 6
7 8 9
Matrix B:
9 8 7
6 5 4
3 2 1
Matrix A + B:
10 10 10
10 10 10
10 10 10
The sum is a matrix of all 10s, because each entry of A plus the corresponding entry of B equals 10. This is a nice sanity check: since A + B are "mirror" matrices (1+9=10, 2+8=10, etc.), the sum should be constant.
With a matrix of zeros:
Enter matrix A (3 rows, 3 columns):
0 0 0
0 0 0
0 0 0
Enter matrix B (3 rows, 3 columns):
1 2 3
4 5 6
7 8 9
Matrix A + B:
1 2 3
4 5 6
7 8 9
The zero matrix is the identity for matrix addition ā adding it to anything leaves the other matrix unchanged, just like adding 0 to a number. This is a useful property to remember: 0 + A = A + 0 = A for matrices, where 0 means the all-zeros matrix.
With negative numbers:
Enter matrix A (3 rows, 3 columns):
-1 2 -3
4 -5 6
-7 8 -9
Enter matrix B (3 rows, 3 columns):
1 -2 3
-4 5 -6
7 -8 9
Matrix A + B:
0 0 0
0 0 0
0 0 0
Here A + B = 0 because B is the negation of A. In matrix algebra, B is the additive inverse of A. Adding a matrix to its inverse gives the zero matrix ā the matrix analog of x + (-x) = 0.
And for the VLA variant:
Enter rows and cols: 2 3
Enter matrix A:
1 2 3
4 5 6
Enter matrix B:
10 20 30
40 50 60
Sum:
11 22 33
44 55 66
A 2Ć3 matrix addition works the same way ā nested loops, elementwise sums, output is the same shape.
Step-by-Step Explanation
Let's trace the algorithm and look at the 2D-array mechanics.
1. How 2D arrays are stored
A 2D array in C is stored in row-major order ā the entire first row comes before the second row, which comes before the third, and so on. For int M[3][3], the elements are stored contiguously as:
M[0][0], M[0][1], M[0][2], M[1][0], M[1][1], M[1][2], M[2][0], M[2][1], M[2][2]
To find the element at [i][j], the compiler computes the offset i * COLS + j elements from the start. This is why the COLS dimension must be known to the compiler ā it's the stride between rows. Without it, the compiler couldn't compute the right offset for M[i][j].
2. The nested loops
for (int i = 0; i < ROWS; i++) ā outer loop over rows. for (int j = 0; j < COLS; j++) ā inner loop over columns. For a 3Ć3 matrix, this visits 9 cells, in this order:
- (0, 0), (0, 1), (0, 2) ā first row
- (1, 0), (1, 1), (1, 2) ā second row
- (2, 0), (2, 1), (2, 2) ā third row
This is the same order as the row-major memory layout, so the loop is cache-friendly ā it walks memory sequentially.
3. The addition
result[i][j] = a[i][j] + b[i][j]; ā one addition per cell. Since the function has three separate arrays, each cell of result is set exactly once, and no cell depends on any other. There's no cross-talk ā this is a pure elementwise operation.
4. Tracing addMatrices with a 2Ć2 example
Suppose A = {{1, 2}, {3, 4}} and B = {{5, 6}, {7, 8}}. The function does:
- i=0, j=0: result[0][0] = 1 + 5 = 6
- i=0, j=1: result[0][1] = 2 + 6 = 8
- i=1, j=0: result[1][0] = 3 + 7 = 10
- i=1, j=1: result[1][1] = 4 + 8 = 12
Result: {{6, 8}, {10, 12}}. Each cell is the sum of the corresponding cells from A and B. Correct.
5. The const qualifiers on input arrays
In void addMatrices(const int a[ROWS][COLS], const int b[ROWS][COLS], int result[ROWS][COLS]), the first two parameters are const ā the function promises not to modify them. This is correct (the function only reads from a and b), and it lets callers pass const arrays without warnings. The third parameter is not const ā that's where the result is written.
6. Why the output is a parameter, not a return value
C functions can't return arrays (or 2D arrays) directly. To return a matrix, you'd have to return a pointer to a dynamically allocated buffer, or return a struct containing the matrix. The simpler and more idiomatic approach is to pass an output array as a parameter and have the function fill it in. This is the same pattern as the swap function from assignment 9 ā pass the output location, not the value.
7. Printing in a grid
printf("%5d", mat[i][j]) prints each element right-aligned in a 5-character field, so all the numbers line up in columns. Then printf("\n") after each row moves to the next line. The result is a proper grid, easy to read at a glance. Without the width specifier, columns would shift depending on how many digits each number has, making the grid harder to parse visually.
8. Dimension compatibility
For matrix addition to be valid, the two input matrices must have the same dimensions. Our program uses the same ROWS and COLS constants for all three matrices, so this is guaranteed. If you were writing a more general version, you'd check the dimensions at runtime and refuse to add mismatched matrices. In a strongly-typed language like C with fixed-size arrays, the compiler enforces compatibility for you ā you can't pass a 3Ć3 array where a 2Ć2 is expected.
9. Complexity
O(ROWS Ć COLS) time and O(1) extra space (beyond the three matrices). For a 3Ć3 matrix, that's 9 additions. For an mĆn matrix, mĆn additions. This is optimal ā you can't add two matrices in fewer than mĆn operations, since every cell must be visited. The algorithm is linear in the number of elements, which is the best possible for this problem.
10. Generalisation to other matrix operations
The nested-loop structure of matrix addition is used in almost every matrix operation:
- Subtraction:
result[i][j] = a[i][j] - b[i][j]. - Scalar multiplication:
result[i][j] = k * a[i][j]. - Elementwise product (Hadamard):
result[i][j] = a[i][j] * b[i][j]. - Transpose:
result[j][i] = a[i][j](note the swapped indices ā a special case). - Matrix multiplication:
result[i][j] += a[i][k] * b[k][j]inside a third inner loop overk. This is the one that breaks the simple elementwise pattern ā it's O(n³) instead of O(n²).
So matrix addition is the simplest and most uniform case. Once you have it, the others are variations on the same theme. Matrix multiplication is the interesting outlier ā the three-loop version where the inner loop computes a dot product ā and that's the natural next step after this assignment.
š Try this: modify the program to compute matrix subtraction instead of addition ā change + to - in the inner loop. Then add a scalar-multiplication function. Then, for a real challenge, try the transpose ā it's a small change but requires swapping the loop indices. Each variation is a small step, and together they build intuition for matrix manipulation.
Frequently Asked Questions
1. Why does the function take three matrix parameters?
Because C functions can't return arrays (or 2D arrays) directly. To "return" a matrix, you pass it as an output parameter. The function reads the two inputs (a and b) and writes the result into the third parameter (result). The caller passes the address of a pre-allocated matrix, and the function fills it in. This is the standard C idiom for any output that's larger than a scalar.
2. Why must the column dimension be specified in the function signature?
Because C uses row-major storage for 2D arrays, and the compiler needs to know the row stride to compute element offsets. a[i][j] lives at memory location base + (i * COLS + j) * sizeof(int), so COLS must be a compile-time constant (or a VLA-bound parameter). The row dimension can be omitted (int a[][COLS]) because it's not used for indexing. This is a quirk of C's 2D array design ā one of the reasons matrix code in C is often verbose.
3. What if the two matrices have different sizes?
In our program, they can't ā we've used the same ROWS and COLS constants for all three matrices, so the compiler enforces compatibility. In a more flexible program (using VLAs or heap allocation), you'd check the dimensions at runtime before calling addMatrices. Adding matrices of different sizes is undefined in standard linear algebra ā you can't pair up the cells. A good program would reject such inputs with an error message, not produce a nonsense result.
4. Can I modify the input matrices in place?
You can, if you pass the same matrix as both an input and the output: addMatrices(A, B, A) would set A[i][j] = A[i][j] + B[i][j], effectively accumulating B into A. This is valid because each cell of A is read before it's written, and no cell depends on another. But it's a subtle behavior ā you're mutating the input. For clarity, use a separate output matrix, or rename the function to something like addInto(A, B) to signal that A is being modified.
5. How is this different from matrix multiplication?
Matrix addition is elementwise: C[i][j] = A[i][j] + B[i][j] ā one operation per cell, O(n²) total. Matrix multiplication is more complex: C[i][j] = sum over k of A[i][k] * B[k][j] ā each cell requires n multiplications and n-1 additions, for a total of O(n³). Matrix multiplication is the more interesting and useful operation, but it's also more error-prone to implement. Addition is the warm-up; multiplication is the real exercise.
6. Can I use float or double for matrix elements?
Yes ā change the element type everywhere: float A[ROWS][COLS], void addMatrices(float a[ROWS][COLS], ...), and use %f in scanf/printf. The loop logic stays the same. Floating-point matrices are common in scientific computing, machine learning, and graphics. The only caveat is that floating-point addition is subject to rounding ā the sum of two floats might not be exactly representable, so comparisons and the printed result may have tiny errors. For most applications this doesn't matter, but for high-precision work you'd use double or a specialized numerical type.
š” Tip: Once this works, try matrix subtraction, scalar multiplication, and transpose ā three easy variations. Then attempt matrix multiplication, which is the "real" matrix operation. It's O(n³) and requires three nested loops (rows, columns, and an inner loop for the dot product). That exercise is a great way to see how the same basic template ā nested loops over cells ā extends to more complex computations. It's the natural next step after this assignment.