Matrix multiplication in C: solved exercise
Matrix multiplication in C: solved exercise
If you searched for a solved matrix multiplication exercise in C, here is the implementation using the ikj loop order (more cache-friendly than the classic ijk order) and element-by-element result verification.
Multiplying matrix A (m×k) by matrix B (k×n) produces C (m×n) where C[i][j] = Σ A[i][p] * B[p][j] for p = 0..k-1. The complexity is O(m·k·n).
Problem statement
Multiply matrix A (3×2) by matrix B (2×4) and display the result C (3×4).
C solution
Expected output
Common mistakes
- Not initializing
Cto zero before accumulating: leftover stack values produce incorrect results. - Using the ijk loop order without thinking about cache: in ijk, the inner loop accesses
B[p][j]withpvarying, jumping across rows in memory (C matrices are row-major). The ikj order keepsB[p][j]in the same row, making sequential access and cache lines efficient. - Getting dimensions wrong:
A[m×k] × B[k×n] = C[m×n]. The number of columns in A must equal the number of rows in B. - Using
intfor large matrices: the product of two 100×100 matrices with values of 1000 can produce entries up to 10^8, withinintrange, but for larger values uselong long.
Practical use
Matrix multiplication is the core of numerical linear algebra, neural networks (forward propagation), 3D graphics (transformations), and scientific computing. Libraries like BLAS implement highly optimized versions with SIMD and multithreading.
Recommended next exercise
- Matrices in C: solved exercises
- Transposed matrix in C: solved exercise
- Sum of main diagonal in C: solved exercise
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
Why is the ikj loop order more efficient than ijk?
Because of cache locality. In ijk, the inner loop accesses B[p][j] with p varying, which jumps across rows in memory (C stores matrices in row-major order). In ikj, the inner loop accesses B[p][j] with j varying, traversing a row sequentially and making full use of loaded cache lines.
How do you verify the multiplication result?
Compute the first elements manually: C[0][0] = A[0][0]*B[0][0] + A[0][1]*B[1][0] = 1*5 + 2*9 = 23. Also check C[2][3] = 5*8 + 6*12 = 40 + 72 = 112.
What is Strassen’s matrix multiplication?
An algorithm that multiplies n×n matrices in O(n^2.807) instead of O(n³), by dividing each matrix into four submatrices and using 7 recursive multiplications instead of 8. In practice it is only used for very large matrices (n > 1000) because the hidden constant is larger than in the standard algorithm.