C Example Code2026-03-152 min read
Multiply two matrices in C using 2D arrays and nested loops. Complete validated source code, dimension validation rules, and complexity breakdown.
Mathematical Principle
Matrix multiplication between matrix A (of dimensions R1 × C1) and matrix B (of dimensions R2 × C2) is possible if and only if the number of columns in A equals the number of rows in B (C1 = R2).
The resulting product matrix C has dimensions $R_1 × C_2$, where each cell is calculated as:
text (ISO Standard)C[i][j] = ∑ (A[i][k] × B[k][j]) for k = 0 to C1 - 1
Complete C Implementation
c (ISO Standard)#include <stdio.h> #define R1 2 #define C1 3 #define R2 3 #define C2 2 void multiplyMatrices(int a[R1][C1], int b[R2][C2], int result[R1][C2]) { /* Initialize all elements of result matrix to 0 */ for (int i = 0; i < R1; i++) { for (int j = 0; j < C2; j++) { result[i][j] = 0; } } /* Triple nested loop to calculate dot products */ for (int i = 0; i < R1; i++) { for (int j = 0; j < C2; j++) { for (int k = 0; k < C1; k++) { result[i][j] += a[i][k] * b[k][j]; } } } } void printMatrix(int rows, int cols, int mat[rows][cols]) { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("%d\t", mat[i][j]); } printf("\n"); } } int main() { int matA[R1][C1] = { {1, 2, 3}, {4, 5, 6} }; int matB[R2][C2] = { {7, 8}, {9, 1}, {2, 3} }; int product[R1][C2]; multiplyMatrices(matA, matB, product); printf("Matrix A (%dx%d):\n", R1, C1); printMatrix(R1, C1, matA); printf("\nMatrix B (%dx%d):\n", R2, C2); printMatrix(R2, C2, matB); printf("\nResultant Product Matrix (%dx%d):\n", R1, C2); printMatrix(R1, C2, product); return 0; }
Expected Output
text (ISO Standard)Matrix A (2x3): 1 2 3 4 5 6 Matrix B (3x2): 7 8 9 1 2 3 Resultant Product Matrix (2x2): 31 19 85 55
Complexity Analysis
- Time Complexity:
O(R1 × C2 × C1) ≈ O(n³)for $n × n$ square matrices. - Space Complexity:
O(R1 × C2)auxiliary space for the output matrix.
Related Tutorials
- Learn how multidimensional memory is laid out in Arrays in C Programming.
- Practice pointer-based algorithms with Bubble Sort in C.