- k loop
- Walks the shared dimension and accumulates into
result[i][j].
Perform Matrix Multiplication in C
What you’ll learn
- The row × column rule: each entry of
ABis a dot product of a row ofAwith a column ofB. - Why three nested loops appear, and why the result buffer must start at zero before accumulating sums.
- A full 3×3 program matching the classic output, a compact 2×2 second example, and a live preview for the 3×3 case.
Overview
Unlike addition, matrix multiplication combines whole rows with whole columns. The middle dimension must line up: columns of the left factor equal rows of the right factor.
Two programs
3×3 reference matrices and a smaller 2×2 product you can trace by hand.
Live preview
Browser math for the same 3×3 inputs as example 1.
Rigor
Dimension rules, complexity, and contrast with element-wise multiply in the FAQ.
Prerequisites
Nested loops and 2D arrays; comfort with summing products in inner loops.
#include <stdio.h>,int main(void),printf, and fixed-size arrays such asint M[3][3].- You already know matrix addition (same shape, add cells). Multiplication follows different rules.
What is matrix multiplication?
If A is m × n and B is n × p, then C = AB is m × p. Entry Cij is the sum, over k from 1 to n, of AikBkj.
In code with zero-based indices: C[i][j] collects sum_k A[i][k] * B[k][j].
Formula
For compatible matrices, Cij = ∑k AikBkj. Each output cell is one dot product: row i of A dotted with column j of B.
n × nBoth factors are n × n, so the product is n × n. The reference programs use n = 3 (and n = 2 in the second example).
Trace one cell
For the 3×3 sample, the top-left result entry uses row 0 of the first matrix and column 0 of the second: 1·9 + 2·6 + 3·3 = 30.
Takeaway: the inner index k is where the first matrix’s column index meets the second matrix’s row index.
Live preview
Uses the same 3×3 integer matrices as example 1. Press the button to print both factors and AB.
Algorithm
Goal: compute C = AB for compatible matrices of fixed sizes known at compile time (here n × n).
Zero the output
Set every result[i][j] to 0 because you will accumulate sums with +=.
Triple loop
For each i and j, add A[i][k]*B[k][j] for all k in the shared dimension.
Display A, B, and C with row-wise printf loops.
📜 Pseudocode
function multiply(A, B, C, n): // n×n matrices
for i from 0 to n - 1:
for j from 0 to n - 1:
C[i][j] ← 0
for k from 0 to n - 1:
C[i][j] ← C[i][j] + A[i][k] * B[k][j] Multiply two 3×3 matrices
Same matrices and output pattern as the reference: multiply_matrices fills result, display_matrix prints with tabs.
#include <stdio.h>
#define N 3
void multiply_matrices(int a[N][N], int b[N][N], int result[N][N]) {
int i, j, k;
for (i = 0; i < N; ++i) {
for (j = 0; j < N; ++j) {
result[i][j] = 0;
}
}
for (i = 0; i < N; ++i) {
for (j = 0; j < N; ++j) {
for (k = 0; k < N; ++k) {
result[i][j] += a[i][k] * b[k][j];
}
}
}
}
void display_matrix(int matrix[N][N]) {
int i, j;
for (i = 0; i < N; ++i) {
for (j = 0; j < N; ++j) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
}
int main(void) {
int first_matrix[N][N] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int second_matrix[N][N] = {
{9, 8, 7},
{6, 5, 4},
{3, 2, 1}
};
int result[N][N];
multiply_matrices(first_matrix, second_matrix, result);
printf("First Matrix:\n");
display_matrix(first_matrix);
printf("\nSecond Matrix:\n");
display_matrix(second_matrix);
printf("\nResult Matrix:\n");
display_matrix(result);
return 0;
} Explanation
The innermost index k pairs a[i][k] with b[k][j]. Initializing result to zero matters because each result[i][j] is a sum of products.
result[i][j] += a[i][k] * b[k][j];Accumulate. One product per k; repeat for all k to finish cell (i,j).
Smaller 2×2 product (easy to check by hand)
Same triple-loop pattern with N = 2. Top-left output is 1·5 + 2·7 = 19, and so on.
#include <stdio.h>
#define N 2
void multiply_matrices(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] = 0;
for (int k = 0; k < N; ++k) {
result[i][j] += a[i][k] * b[k][j];
}
}
}
}
void display_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("%d ", m[i][j]);
}
printf("\n");
}
}
int main(void) {
int a[N][N] = {
{1, 2},
{3, 4}
};
int b[N][N] = {
{5, 6},
{7, 8}
};
int r[N][N];
multiply_matrices(a, b, r);
display_matrix("A", a);
printf("\n");
display_matrix("B", b);
printf("\n");
display_matrix("AB", r);
return 0;
} Explanation
Combining zero-init with the k loop in one nest is a compact variant; mathematically it matches example 1.
Notes for larger problems
Non-square factors. Generalize loop bounds: i < rowsA, j < colsB, k < colsA (must equal rowsB).
Speed. Researchers use blocked (tile) multiplication and SIMD for huge matrices; interviews usually focus on correct triple loops first.
❓ FAQ
🔄 Input / output
Examples use literals in main. To accept typed input, add nested scanf loops and verify dimensions before multiplying.
Edge cases
Rules that trip beginners:
Inner dimensions
You cannot multiply m×n by p×q unless n = p.
AB vs BA
Matrix multiplication is not commutative in general: AB and BA can differ.
Integer products
Intermediate products may overflow int; consider wider types for big inputs.
⏱️ Time and space complexity
| Setting | Time | Extra space |
|---|---|---|
Two n × n matrices, classic triple loop | O(n3) | O(1) beyond outputs |
m×n by n×p | O(m · n · p) | O(1) beyond outputs |
Summary
- Rule:
Cij = sumk AikBkj; inner sizes ofAandBmust match. - Code: zero
result, then three nested loops with+= a[i][k]*b[k][j]. - Complexity: cubic in
nfor squaren×nmatrices.
Matrix multiplication links rows of A with columns of B. You need A to be m × n and B to be n × p—the two n’s must match—then AB is m × p.
8 people found this page helpful
