/* 12(a&b) W.A.P to read M and N of a matrix A(M x N) and P and Q of matrix B(P x Q). Check if A and B are multiplicable. If so, read the elements of A and B, multiply and print the elements of the resultant matrix. Calculate the trace of the resultant matrix. */
#include <stdio.h>
#include <conio.h>
void main()
{
/* Variable Declarations */
int m1[10][10],m2[10][10],m3[10][10],i,j,k,m,n,x,y,trace=0;
clrscr();
printf("Enter row and column of a matrix-1 : ");
scanf("%d,%d",&m,&n);
printf("\n\nEnter row and column of a matrix-2 : ");
scanf("%d,%d",&x,&y);
if ((m!=0) && (n!=0) && (x!=0) && (y!=0))
{
if (n==x) /* Check whether Matrix multiplication is possible or not */
{
printf("\n\nEnter elements for matrix m1\n");
for (i=0; i<m; i++)
{
for (j=0; j<n; j++)
{
scanf("%d",&m1[i][j]);
}
}
printf("\n\nEnter elements for matrix m2\n");
for (i=0; i<x; i++)
{
for (j=0; j<y; j++)
{
scanf("%d",&m2[i][j]);
}
}
/* Matrix Multiplication m3 = m1 * m2 */
for (i=0; i<m; i++)
{
for (j=0; j<y; j++)
{
m3[i][j] = 0;
for (k=0; k<n; k++)
{
m3[i][j] = m3[i][j] + m1[i][k] * m2[k][j];
}
}
}
printf("\n\nResult of the Multiplication of a Matrix is as follows :\n");
for (i=0; i<m; i++)
{
for (j=0; j<y; j++)
{
printf("%d\t",m3[i][j]);
}
printf("\n");
}
if (m==y) /* Trace the resultant matrix */
{
printf("\n\nTrace of the Resultant Matrix is possible.\n");
for (i=0; i<m; i++)
{
trace=trace+m3[i][i];
}
printf("\nTrace of the resultant matrix is %d",trace);
}
else printf("\n\n!!! Trace of the Resultant Matrix is not possible. !!!\n");
}
else
{
printf("\n\nMatrix Multiplication is Not Possible\a\a");
}
}
else printf("\n !!! Invalid Input Entry. Please Try Again !!!");
getch();
}