-
Can Anyone...
Can anyone please debug this simple program of mine. It takes two 3*3 matrices and multiplies them. Everything is right, except that when the 2nd matrix gets printed, the first element is printed as a muliple of 4. I can't find anything wrong.
Code:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3]={0,0,0,0,0,0,0,0,0};
int j,i,x,y; clrscr();
x=y=0;
for(i=0;i<=2;i++) /* Initialize 1st Matrix */
for(j=0;j<=2;j++)
scanf("%d",&a[i][j]);
for(i=0;i<=2;i++) /* Initialize 2nd Matrix */
for(j=0;j<=2;j++)
scanf("%d",&b[i][j]);
for(;x<=2;y++)
{ if(y==3)
{x++; y=0;} /* Multiply the two matrices and store them in c */
for(j=0;j<=2;j++)
{
c[x][y]+=(a[x][j]*b[j][y]);
}
}
printf("\n1st Matrix\n"); /* Print 1st Matrix */
for(i=0;i<=2;i++)
{ for(j=0;j<=2;j++)
printf("%d ",a[i][j]);
printf("\n");
}
printf("\n2nd Matrix\n"); /* Print 2nd Matrix */
for(i=0;i<=2;i++)
{ for(j=0;j<=2;j++)
printf("%d ",b[i][j]);
printf("\n");
}
printf("\nFinal Matrix\n"); /* Print Multiplied Matrix */
for(i=0;i<=2;i++)
{ for(j=0;j<=2;j++)
printf("%d ",c[i][j]);
printf("\n");
}
}
-
Firstly, void main() is wrong. You need to do int main( void ), and return zero at the end of your program to signal successful completion. Why void main() is wrong.
Secondly, your code will not compile on my machine because "i" is undeclared.
Thirdly, you never initialize the entries in matrix c, meaning they will start off filled with junk. You then add the results of your multiplications to that junk, which leaves you with more junk.
-
There's nothing wrong with this loop, but it's highly unconventional to use <= SIZE-1. It's preferable to use
Code:
for (i = 0; i < 3; i++)
since the 3 matches the size you use to declare you matrices. Better yet, use named constants:
Code:
#define ROWS 3
#define COLS 3
int main(void)
{
int a[ROWS][COLS], ...
for (i = 0; i < ROWS; i++)
for(j = 0; j < COLS; j++)
...
Code:
for(;x<=2;y++)
{ if(y==3)
{x++; y=0;} /* Multiply the two matrices and store them in c */
for(j=0;j<=2;j++)
{
c[x][y]+=(a[x][j]*b[j][y]);
}
}
That is the most confusing loop I've ever seen, and is the cause of your "first element of b" error. You can get into the loop when x is 2, which is a valid index, but if y is 3, you increment x to 3 and make it out-of-bounds, then you go and write to c[x][y]. Also, you never initialize c to all zeros, so you are starting with garbage values and adding to that. Try
Code:
int c[ROWS][COLS] = {{0}};
Lastly, your use of conio.h and clrscr suggest you're using Turbo C. I would recommend getting an up-to-date compiler like Pelles C, Code::Blocks with MinGW or MS Visual Studio Express, all of which are free, current and far superior products overall.
-