Program 6
Implement
Matrix Multiplication algorithm with proper validation
of multiplication rules. Matrix multiplication is only possible when the number of
columns in the first matrix equals the number of
rows in the second matrix. The resulting matrix will have
dimensions equal to the rows of the first matrix and columns of the second matrix.
⚠️ Multiplication Rule: Matrix A(m×n) × Matrix B(p×q) is valid only if n = p
Algorithm
- Initialize: Start the program and declare matrix arrays and variables
- Input Dimensions: Read rows and columns for both matrices (r1, c1, r2, c2)
- Validate Rule: Check if c1 == r2, if not, display error and exit
- Input Matrix A: Read elements of first matrix (r1 × c1)
- Input Matrix B: Read elements of second matrix (r2 × c2)
- Initialize Result: Set all elements of result matrix C to 0
- Triple Loop: For each i, j, k: C[i][j] += A[i][k] × B[k][j]
- Display Result: Print the resultant matrix C (r1 × c2)
- Terminate: End the program
Flowchart
START
→
Input Dimensions
→
Validate c1==r2
→
Input Matrices
→
Initialize C[i][j]=0
→
Triple Loop Multiply
→
Display Result
→
STOP
Code
#include <stdio.h>
int main() {
int a[10][10], b[10][10], c[10][10];
int r1, c1, r2, c2, i, j, k;
// Input matrix sizes
printf("Enter rows and columns of first matrix: ");
scanf("%d %d", &r1, &c1);
printf("Enter rows and columns of second matrix: ");
scanf("%d %d", &r2, &c2);
// Validate multiplication rule
if (c1 != r2) {
printf("Matrix multiplication not possible!\n");
printf("Rule: Columns of first matrix must equal rows of second matrix.\n");
return 0;
}
// Input matrices
printf("Enter elements of first matrix:\n");
for (i = 0; i < r1; i++)
for (j = 0; j < c1; j++)
scanf("%d", &a[i][j]);
printf("Enter elements of second matrix:\n");
for (i = 0; i < r2; i++)
for (j = 0; j < c2; j++)
scanf("%d", &b[i][j]);
// Initialize result matrix to 0
for (i = 0; i < r1; i++)
for (j = 0; j < c2; j++)
c[i][j] = 0;
// Matrix multiplication
for (i = 0; i < r1; i++) {
for (j = 0; j < c2; j++) {
for (k = 0; k < c1; k++) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
// Display result
printf("Resultant Matrix:\n");
for (i = 0; i < r1; i++) {
for (j = 0; j < c2; j++) {
printf("%d ", c[i][j]);
}
printf("\n");
}
return 0;
}
Replay !
Share Your Thoughts