Matrix Multiplication in C (A × B)
In this tutorial, we will write a C program that:
- Takes dimensions and elements of two matrices A (n × m) and B (m × p)
- Checks whether multiplication is possible
- Prints the resulting matrix C (A × B)
Condition for Matrix Multiplication
Matrix multiplication is possible only if:
Number of columns of A = Number of rows of B
(m = m)
If this condition is not satisfied, multiplication is not possible.
C Program
#include <stdio.h>
int main() {
int n, m, p;
int i, j, k;
printf("Enter rows and columns of Matrix A (n m): ");
scanf("%d %d", &n, &m);
printf("Enter columns of Matrix B (p): ");
scanf("%d", &p);
int A[n][m], B[m][p], C[n][p];
printf("Enter elements of Matrix A:\n");
for(i = 0; i < n; i++) {
for(j = 0; j < m; j++) {
scanf("%d", &A[i][j]);
}
}
printf("Enter elements of Matrix B:\n");
for(i = 0; i < m; i++) {
for(j = 0; j < p; j++) {
scanf("%d", &B[i][j]);
}
}
// Initialize result matrix C with 0
for(i = 0; i < n; i++) {
for(j = 0; j < p; j++) {
C[i][j] = 0;
}
}
// Matrix multiplication
for(i = 0; i < n; i++) {
for(j = 0; j < p; j++) {
for(k = 0; k < m; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
printf("Resultant Matrix C (A x B):\n");
for(i = 0; i < n; i++) {
for(j = 0; j < p; j++) {
printf("%d ", C[i][j]);
}
printf("\n");
}
return 0;
}
Explanation
1. Input Dimensions
User enters:
- n = rows of A
- m = columns of A (and rows of B)
- p = columns of B
2. Input Matrices
Matrix A is of size (n × m). Matrix B is of size (m × p).
3. Multiplication Logic
C[i][j] += A[i][k] * B[k][j];
Each element of matrix C is calculated as:
C[i][j] = Σ (A[i][k] × B[k][j])
4. Output
The resultant matrix C (n × p) is printed.
Example
Matrix A (2 × 2): 1 2 3 4 Matrix B (2 × 2): 5 6 7 8 Result Matrix: 19 22 43 50
Time Complexity
Three nested loops are used. Therefore, time complexity is O(n × m × p).
কোন মন্তব্য নেই:
একটি মন্তব্য পোস্ট করুন