Program 13:
Develop a program to perform Matrix Multiplication.
Algorithm:
1. Start
2. Declare matrices:
A[r1][c1], B[r2][c2], res[r1][c2]
3. Read values of r1, c1 (rows and columns of Matrix A)
4. Read values of r2, c2 (rows and columns of Matrix B)
5. Check condition:
If c1 ≠ r2:
1. Print "Multiplication not possible"
2. Stop
6. Input elements of matrix A
7. Input elements of matrix B
8. Initialize result matrix res[i][j] = 0 for all i, j
9. Perform multiplication:
For each row i from 0 to r1 - 1:
1. For each column j from 0 to c2 - 1:
For each k from 0 to c1 - 1:
res[i][j] = res[i][j] + (A[i][k] * B[k][j])
10. Display the resultant matrix res
11. Stop
Code:
#include<stdio.h>
int main()
{
int a[10][10], b[10][10], res[10][10], r1, c1, r2, c2;
printf("Enter rows and columns for Matrix 1: ");
scanf("%d %d", &r1, &c1);
printf("Enter rows and columns for Matrix 2: ");
scanf("%d %d", &r2, &c2);
if (c1!= r2)
{
printf("Multiplication not possible!\n");
return 0;
}
printf("Enter elements of Matrix 1:\n");
for(int i=0; i<r1; i++)
for(int j=0; j<c1; j++)
scanf("%d", &a[i][j]);
printf("Enter elements of Matrix 2:\n");
for(int i=0; i<r2; i++)
for(int j=0; j<c2; j++)
scanf("%d", &b[i][j]);
for(int i=0; i<r1; i++)
{
for(int j=0; j<c2; j++)
{
res[i][j] = 0;
for(int k=0; k<c1; k++)
res[i][j] += a[i][k] * b[k][j];
}
}
printf("Resulting Matrix:\n");
for(int i=0; i<r1; i++)
{
for(int j=0; j<c2; j++)
printf("%d ", res[i][j]);
printf("\n");
}
return 0;
}
Output:
Enter rows and columns for Matrix 1: 2 3
Enter rows and columns for Matrix 2: 4 2
Multiplication not possible!
Enter rows and columns for Matrix 1: 2 2
Enter rows and columns for Matrix 2: 2 2
Enter elements of Matrix 1:
12
34
Enter elements of Matrix 2:
56
78
Resulting Matrix:
19 22
43 50
Enter rows and columns for Matrix 1: 2 3
Enter rows and columns for Matrix 2: 3 2
Enter elements of Matrix 1:
111
222
Enter elements of Matrix 2:
12
34
56
Resulting Matrix:
9 12
18 24