C Program Matrix Multiplication

By | March 14, 2020

C Program Matrix Multiplication

C Program Matrix Multiplication, multiply two matrices

```/* C program to multiplication two matrices

Matrix Multiplication

www.easyCodeBook.com

*/
#include <stdio.h>

int main()
{
int m, n, p, q, i, j, k;
int matrix1[10][10], matrix2[10][10], multiplication[10][10];

printf("Enter number of rows and columns of matrix1\n");
scanf("%d%d", &m, &n);

printf("Enter number of rows and columns of matrix2\n");
scanf("%d%d", &p, &q);

if (n != p)
{
printf("Since number of columns of first matrix\n");
printf("is not equal to number of rows of second matrix,\n");
printf("hence both matrices are not multiplication compatible,\n");
printf("and we cannot multiply these matrices.\n");
return 0;
}
printf("Enter %d elements of matrix1 of %dx%d\n",m*n,m,n);

for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &matrix1[i][j]);

printf("Enter %d elements of matrix2 of %dx%d\n",p*q,p,q);

for (i = 0; i < p; i++)
for (j = 0; j < q; j++)
scanf("%d", &matrix2[i][j]);

for (i = 0; i < m; i++)
for (j = 0; j < q; j++)
{
multiplication[i][j]=0;
for (k = 0; k < p; k++)
multiplication[i][j] = multiplication[i][j] + matrix1[i][k]*matrix2[k][j];
}

printf("Product / Multiplication of the two matrices is as follows:\n");

for (i = 0; i < m; i++)
{
for (j = 0; j < q; j++)
printf("%d\t", multiplication[i][j]);

printf("\n");
}

return 0;
}
```

Output

Enter number of rows and columns of matrix1
2
2
Enter number of rows and columns of matrix2
2
2
Enter 4 elements of matrix1 of 2×2
-1
4
2
3
Enter 4 elements of matrix2 of 2×2
9
-3
6
1
Product / Multiplication of the two matrices is as follows:

```15      7
36      -3
```

Note: You can Enter a 2×2 matrix as

```-1
4
2
3
or as
-1 4 2 3
```

Output 2:
Enter number of rows and columns of matrix1

2
2
Enter number of rows and columns of matrix2
2
2
Enter 4 elements of matrix1 of 2×2
-1 4 2 3
Enter 4 elements of matrix2 of 2×2
9 -3 6 1
Product / Multiplication of the two matrices is as follows:

```15      7
36      -3
```

1,086 total views,  5 views today