I wrote the following code in C to read two (3*3) square matrices, multiply them
ID: 3620473 • Letter: I
Question
I wrote the following code in C to read two (3*3) square matrices, multiply them & display the result matrix. It gets complied well & run too. But the result matrix which is displayed is a mess, with so many numbers. Can anyone please help me to find the problem in this code? or is there any other good way to do this? Thank you...#include<stdio.h>
int main(){
int no,row,column,m1[3][3],m2[3][3],m[3][3],x,y,z;
printf("Enter the first matrix elements from left to right in a row one at a time");
for(row=0;row<3;row++){
for(column=0;column<3;column++){
scanf("%d",&m1[row][column]);
}
}
printf("Enter the second matrix elements too");
for(row=0;row<3;row++){
for(column=0;column<3;column++){
scanf("%d",&m2[row][column]);
}
}
for(row=0;row<3;row++){
for(column=0;column<3;column++){
for(x=0;x<3;x++){
m[row][column]+=((m1[row][x])*(m2[x][column]));
}
}
}
printf("%d",m[0][0]);
}
Explanation / Answer
please rate - thanks your basic problem was you didn't initialize the answer matrix to 0 #include<stdio.h>#include<conio.h>
int main(){
int no,row,column,m1[3][3],m2[3][3],m[3][3]={0},x,y,z;
printf("Enter the first matrix elements from left to right in a row one at a time");
for(row=0;row<3;row++){
for(column=0;column<3;column++){
scanf("%d",&m1[row][column]);
}
}
printf("Enter the second matrix elements too");
for(row=0;row<3;row++){
for(column=0;column<3;column++){
scanf("%d",&m2[row][column]);
}
}
printf("The starting matrices: ");
for(x=0;x<3;x++)
{for(y=0;y<3;y++)
printf("%2d ",m1[x][y]);
printf(" ");
for(y=0;y<3;y++)
printf("%2d ",m2[x][y]);
printf(" ");
}
for(row=0;row<3;row++){
for(column=0;column<3;column++){
for(x=0;x<3;x++){
m[row][column]+=((m1[row][x])*(m2[x][column]));
}
}
}
printf("The final Matrix ");
for(x=0;x<3;x++)
{for(y=0;y<3;y++)
printf("%2d ",m[x][y]);
printf(" ");
}
getch();
}