Multiply Two Matrices using 2D Arrays in C
To multiply two matrices using 2D arrays in C, we use nested loops to compute the dot product of corresponding rows and columns. The multiplication of an m x n
matrix with an n x p
matrix results in an m x p
matrix. Each element in the resultant matrix is calculated as the sum of the product of corresponding elements from the row of the first matrix and the column of the second matrix.
Examples of Matrix Multiplication
1. Basic Matrix Multiplication (2×2 Matrices)
In this example, we will multiply two 2×2 matrices and store the result in another 2×2 matrix.
main.c
#include <stdio.h>
int main() {
int A[2][2] = {{1, 2}, {3, 4}};
int B[2][2] = {{5, 6}, {7, 8}};
int C[2][2] = {0}; // Resultant matrix initialized to zero
// Performing matrix multiplication
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
// Displaying the result
printf("Resultant Matrix:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", C[i][j]);
}
printf("\n");
}
return 0;
}
Explanation:
- We define two 2×2 matrices
A
andB
with given values. - We initialize an empty 2×2 matrix
C
to store the result. - Using three nested loops:
- Outer loop iterates over the rows of matrix
A
. - Middle loop iterates over the columns of matrix
B
. - Inner loop computes the sum of products for the corresponding row and column.
- Outer loop iterates over the rows of matrix
- We print the resultant matrix.
Output:
19 22
43 50
2. Matrix Multiplication (3×3 Matrices)
In this example, we extend matrix multiplication to a 3×3 matrix.
main.c
#include <stdio.h>
int main() {
int A[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int B[3][3] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int C[3][3] = {0};
// Performing matrix multiplication
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 3; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
// Displaying the result
printf("Resultant Matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", C[i][j]);
}
printf("\n");
}
return 0;
}
Explanation:
- We define two 3×3 matrices
A
andB
. - We initialize a 3×3 matrix
C
to store the results. - Three nested loops calculate the dot product for each row and column.
- Finally, we print the resultant matrix.
Output:
30 24 18
84 69 54
138 114 90
Conclusion
In this tutorial, we learned how to multiply matrices using 2D arrays in C:
- Understanding matrix multiplication: We saw how multiplying an
m x n
matrix with ann x p
matrix results in anm x p
matrix. - Using nested loops: We iterated through the rows of the first matrix and the columns of the second matrix.
- Practical examples: We implemented multiplication for both 2×2 and 3×3 matrices.
Matrix multiplication is an essential concept in computer science, widely used in graphics, engineering, and machine learning applications.