I\'m trying to solve a matrix multiplication problem with C. Matrix sizes given in problem (2x2) I wrote this code but it doesn\'t print result as I expect. I think I\'m missing
You can have matrix multiplication of any given size by user in the following manner :
#include<stdio.h>
void main()
{
int r1, c1, r2, c2;
printf("Enter number of rows and columns for matrix A : ");
scanf("%d %d",&r1,&c1);
printf("Enter number of rows and columns for matrix B : ");
scanf("%d %d",&r2,&c2);
int a[r1][c1], b[r2][c2], ab[r1][c2], ba[r2][c1],i,j,k,temp;
if(c1==r2 && r1==c2)
{
printf("\nEnter element in matrix A : ");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("\n Enter element : ");
scanf("%d",&a[i][j]);
}
}
printf("\nEnter element in B : ");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
printf("\nEnter element : ");
scanf("%d",&b[i][j]);
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
temp=0;
for(k=0;k<r2;k++)
{
temp+=a[i][k]*b[j][k];
}
ab[i][j]=temp;
}
}
for(i=0;i<r2;i++)
{
for(j=0;j<c1;j++)
{
temp=0;
for(k=0;k<r1;k++)
{
temp+=b[i][k]*a[k][j];
}
ba[i][j]=temp;
}
}
printf("\nMatrix A : ");
for(i=0;i<r1;i++)
{
printf("\n\t");
for(j=0;j<c1;j++)
{
printf("%d",a[i][j]);
}
printf("\n");
}
printf("\nMatrix B : ");
for(i=0;i<r2;i++)
{
printf("\n\t");
for(j=0;j<c2;j++)
{
printf("%d",b[i][j]);
}
}
printf("\nMatrix multiplication of A*B : ");
for(i=0;i<r1;i++)
{
printf("\n\t");
for(j=0;j<c2;j++)
{
printf("\t%d",ab[i][j]);
}
printf("\n");
}
printf("\nMatrix multiplication of B*A : ");
for(i=0;i<r2;i++)
{
printf("\n\t");
for(j=0;j<c1;j++)
{
printf("\t%d",ba[i][j]);
}
printf("\n");
}
}
else
printf("\nMatrix Multiplication is not possible...!!!");
}
You should initialize matC
to all zeroes.