A matrix is a rectangular table of numbers, and in C it is naturally stored as a 2D array. Matrix operations appear everywhere: in SSC and HSC higher mathematics, computer graphics, spreadsheets, and the calculations behind machine learning. This lesson writes the core operations in C: addition, multiplication, transpose, the identity matrix and the determinant, and shows how to pass matrices of any size to a function.
In this lesson you will learn
- Passing 2D arrays to functions
- Matrix addition and transpose
- Matrix multiplication with three nested loops
- Why A × B usually differs from B × A
- Variable-size matrices, the trace and a 3 × 3 determinant
You should know multidimensional arrays and functions. Our dynamic 2D arrays lesson shows how to create matrices whose size is decided at run time.
Add, Multiply and Transpose
#include <stdio.h>
#define N 3
void print_matrix(const char *title, int m[N][N]) {
printf("%s\n", title);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
printf("%5d", m[i][j]);
printf("\n");
}
}
void add(int a[N][N], int b[N][N], int out[N][N]) {
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
out[i][j] = a[i][j] + b[i][j];
}
void multiply(int a[N][N], int b[N][N], int out[N][N]) {
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++) {
int sum = 0;
for (int k = 0; k < N; k++)
sum += a[i][k] * b[k][j]; /* row i of a times column j of b */
out[i][j] = sum;
}
}
void transpose(int a[N][N], int out[N][N]) {
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
out[j][i] = 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 I[N][N] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
int R[N][N];
add(A, B, R);
print_matrix("A + B:", R);
multiply(A, B, R);
print_matrix("A x B:", R);
multiply(B, A, R);
print_matrix("B x A (different!):", R);
multiply(A, I, R);
print_matrix("A x I (identity leaves A unchanged):", R);
transpose(A, R);
print_matrix("transpose of A:", R);
return 0;
}
Output
A + B:
10 10 10
10 10 10
10 10 10
A x B:
30 24 18
84 69 54
138 114 90
B x A (different!):
90 114 138
54 69 84
18 24 30
A x I (identity leaves A unchanged):
1 2 3
4 5 6
7 8 9
transpose of A:
1 4 7
2 5 8
3 6 9
- A function parameter written as
int m[N][N]receives a pointer to the first row. The column countNmust be known so that C can findm[i][j]. - Addition adds matching positions. Every entry of A + B is 10, because each pair of numbers adds up to 10.
- Multiplication: entry
[i][j]of the result is rowiof A multiplied, item by item, with columnjof B, then summed. For example, the top-left entry is 1×9 + 2×6 + 3×3 = 30. This takes three nested loops, so multiplying two n × n matrices needs about n³ multiplications. - B × A gives a different answer from A × B. Matrix multiplication is not commutative, so the order matters.
- The identity matrix I has 1s on the main diagonal and 0s elsewhere. Multiplying by it leaves a matrix unchanged, just as multiplying a number by 1 does.
- The transpose swaps rows and columns:
out[j][i] = a[i][j].
Matrices of Any Size
#include <stdio.h>
/* Variable-size matrices: pass the sizes first, then the arrays */
void multiply(int r1, int c1, int c2,
const double a[r1][c1], const double b[c1][c2], double out[r1][c2]) {
for (int i = 0; i < r1; i++)
for (int j = 0; j < c2; j++) {
out[i][j] = 0;
for (int k = 0; k < c1; k++)
out[i][j] += a[i][k] * b[k][j];
}
}
double det3(const double m[3][3]) {
return m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1])
- m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
+ m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]);
}
int main(void) {
/* Shop sales: 2 shops x 3 products (units sold) */
const double units[2][3] = {{10, 4, 6}, {3, 12, 5}};
/* Each product: price and profit per unit (3 products x 2 values) */
const double money[3][2] = {{50, 8}, {120, 30}, {80, 15}};
double result[2][2];
multiply(2, 3, 2, units, money, result);
for (int s = 0; s < 2; s++)
printf("shop %d: sales %.0f taka, profit %.0f taka\n", s + 1, result[s][0], result[s][1]);
const double m[3][3] = {{2, 0, 1}, {1, 3, 2}, {1, 1, 2}};
printf("determinant = %.0f\n", det3(m));
/* Sum of the main diagonal (the trace) */
double trace = 0;
for (int i = 0; i < 3; i++) trace += m[i][i];
printf("trace = %.0f\n", trace);
return 0;
}
Output
shop 1: sales 1460 taka, profit 290 taka
shop 2: sales 1990 taka, profit 459 taka
determinant = 6
trace = 7
- By putting the sizes first,
multiply(int r1, int c1, int c2, const double a[r1][c1], ...)accepts matrices of any shape. An r1 × c1 matrix times a c1 × c2 matrix gives an r1 × c2 result; the inner sizes must match. - The practical example multiplies a 2 × 3 table of units sold by a 3 × 2 table of price and profit per product. The result is a 2 × 2 table holding each shop’s total sales and profit, all from one multiplication. Shop 1 sold 10 × 50 + 4 × 120 + 6 × 80 = 1,460 taka.
det3works out a 3 × 3 determinant by expanding along the first row, the method taught in higher mathematics. A determinant of 0 would mean the matrix has no inverse.- The trace is the sum of the main diagonal: 2 + 3 + 2 = 7.
Operation Rules
| Operation | Size rule | Work for n × n |
|---|---|---|
| A + B | Same size | n² additions |
| A × B | Columns of A = rows of B | n³ multiplications |
| Transpose | r × c becomes c × r | n² copies |
| Determinant | Square only | Formula for 2 × 2 and 3 × 3; elimination for larger |
Common Mistakes
- Writing the result into one of the inputs, such as
multiply(A, B, A). The function overwrites values it still needs; use a separate output matrix. - Forgetting to reset the sum to 0 for each result entry.
- Mixing up the loop order so the code multiplies rows by rows instead of rows by columns.
- Using
intfor large values, which can overflow. Uselong longordoublewhen entries are big.
Practice Exercises
Exercise 1. Write a function that returns 1 if a 3 × 3 matrix is symmetric, meaning it equals its own transpose.
Show answer
int is_symmetric(int m[3][3]) {
for (int i = 0; i < 3; i++)
for (int j = i + 1; j < 3; j++)
if (m[i][j] != m[j][i]) return 0;
return 1;
}
Exercise 2. Write det2 for a 2 × 2 matrix and use it to check that the matrix {{4, 7}, {2, 6}} has an inverse.
Show answer
double det2(const double m[2][2]) {
return m[0][0] * m[1][1] - m[0][1] * m[1][0];
}
/* det2({{4, 7}, {2, 6}}) = 24 - 14 = 10, not 0, so an inverse exists */
Frequently Asked Questions
How do real programs multiply very large matrices?
They use optimised libraries such as BLAS, which reorder the loops to use the CPU cache well, run on many cores and use special instructions. The simple triple loop is correct but much slower for big matrices.
Can I return a matrix from a function?
Not a plain 2D array. Either pass an output array as a parameter, as this lesson does, wrap the array in a struct, or allocate the result on the heap and return a pointer.
Summary
- Matrices are 2D arrays; functions need the column count to index them.
- Addition works position by position; multiplication combines rows with columns.
- A × B and B × A are usually different.
- Put sizes first in the parameter list to handle matrices of any shape.
