Write a C program to perform matrix multiplication.
#include <stdlib.h>
int main() {
int row1, row2, col1, col2, i, j, k, sum = 0;
int **mat1, **mat2, **output;
/* Enter the number of rows and columns for i/p matrix1 */
printf("Enter the row and column for matrix1:");
scanf("%d%d", &row1, &col1);
/* dynamically allocate memory for matrix 1 */
mat1 = (int **)malloc(sizeof (int) * row1);
for (i = 0; i < row1; i++)
mat1[i] = (int *)malloc(sizeof (int) * col1);
/* get matrix1 entries from user */
printf("Enter your data for matrix1:\n");
for (i = 0; i < row1; i++)
for (j = 0; j <col1; j++) {
scanf("%d", &mat1[i][j]);
}
/* get the no of rows and columns for matrix2 */
printf("Enter the row and column for matrix2:");
scanf("%d%d", &row2, &col2);
if (col1 != row2) {
printf("Error:matrix multiplication rule violated!!\n");
return 0;
}
/* dynamically allocate memory for matrix2 entries */
mat2 = (int **)malloc(sizeof (int) * row2);
for (i = 0; i < row2; i++)
mat2[i] = (int *)malloc(sizeof (int) * col2)
/* get matrix2 entries from user */
printf("Enter your data for matrix2:\n");
for (i = 0; i < row2; i++)
for (j = 0; j <col2; j++) {
scanf("%d", &mat2[i][j]);
}
/* dynamically allocate memory for output matrix */
output = (int **)calloc(1, sizeof (int) * row1);
for (i = 0; i < row1; i++)
output[i] = (int *)calloc(1, sizeof (int) * col2);
/* matrix multiplication */
for (i = 0; i < row1; i++) {
for (j = 0; j < col2; j++) {
for (k = 0; k < row2; k++) {
output[i][j] =
output[i][j] + (mat1[i][k] * mat2[k][j]);
}
}
}
/* print the result */
printf("Output:\n");
for (i = 0; i < row1; i++) {
for (j = 0; j < col2; j++)
printf("%3d ", output[i][j]);
printf("\n");
}
return 0;
}
Output:
jp@jp-VirtualBox:~/cpgms/lab_pgms/06_arrays$ ./a.out
Enter the row and column for matrix1:3 3
Enter your data for matrix1:
10 10 10
10 10 10
10 10 10
Enter the row and column for matrix2:3 3
Enter your data for matrix2:
20 20 20
20 20 20
20 20 20
Output:
600 600 600
600 600 600
600 600 600
Enter the row and column for matrix1:3 3
Enter your data for matrix1:
10 10 10
10 10 10
10 10 10
Enter the row and column for matrix2:3 3
Enter your data for matrix2:
20 20 20
20 20 20
20 20 20
Output:
600 600 600
600 600 600
600 600 600
No comments:
Post a Comment