Matrix multiplication is a cornerstone of programming, used in graphics, data science, and engineering. If you’re learning C, mastering this concept will boost your coding skills. In this guide, we’ll break down matrix multiplication in C using simple language, practical code examples, and real-life applications. Let’s get started!
What is Matrix Multiplication?
Matrix multiplication involves multiplying two matrices to produce a third matrix. Unlike simple arithmetic, it follows specific rules:
Rule 1: The number of columns in the first matrix must equal the rows in the second matrix.
– Rule 2: The resulting matrix has the same rows as the first matrix and the same columns as the second matrix.
Example:
If Matrix A is 2×3 and Matrix B is 3×2, the result will be a 2×2 matrix.
Step-by-Step C Program for Matrix Multiplication
Let’s write a C program to multiply two matrices. We’ll use a x3 matrix for simplicit
#include <stdio.h>
int main() {
int a[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // First matrix
int b[3][3] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}}; // Second matrix
int result[3][3]; // Result matrix
int i, j, k;
// Multiply matrices
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
result[i][j] = 0; // Initialize to 0
for (k = 0; k < 3; k++) {
result[i][j] += a[i][k] * b[k][j];
}
}
}
// Print result
printf("Result:\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
OutPut
Result:
30 24 18
84 69 54
138 114 90
Explanation:
i
iterates over rows of the first matrix.j
iterates over columns of the second matrix.k
handles the element-wise multiplication and summation.result
is set to 0
before calculation to avoid garbage values.For matrices of variable sizes, use dynamic memory allocation with malloc
:
#include <stdio.h>
#include <stdlib.h>
int main() {
int rows1 = 2, cols1 = 3; // Matrix A: 2x3
int rows2 = 3, cols2 = 2; // Matrix B: 3x2
// Allocate memory
int **a = (int **)malloc(rows1 * sizeof(int *));
int **b = (int **)malloc(rows2 * sizeof(int *));
int **result = (int **)malloc(rows1 * sizeof(int *));
// Initialize matrices (code for input omitted for brevity)
// ... perform multiplication ...
// Free memory after use
free(a);
free(b);
free(result);
return 0;
}
Test your understanding with these exercises:
The result matrix must start at 0 to correctly accumulate the sum of products. Otherwise, garbage values will distort the result.
No! The columns of the first matrix (3) must match the rows of the second matrix (2).
Use dynamic memory allocation (like malloc
in C) to avoid stack overflow.
O(n³) for two n x n matrices due to three nested loops.
Try coding these examples yourself, and experiment with the practice questions.