Reputation: 1
I am trying to multiply 2 dimensional matrices in C language. I have furnished below the code for your reference. When I try to print 'myC', I keep getting zeros out. Where am i going wrong ? I've tried multiple things and still can not figure this out. Has anyone got ideas, that would be greatly appreciated.
#include <stdio.h>
#define mysize 4
int myA[mysize][mysize];
int myC[mysize][mysize];
int i,k;
int j,l;
int total;
int iLimit;
int jLimit;
void printMatrix(int iLimit,int jLimit,int myA[iLimit][jLimit]){
i=0;
while (i<iLimit){
j=0;
while (j<jLimit){
printf ("%7d", myA[i][j]);
j=j+1;
}
printf ("\n");
i=i+1;}
}
int main(void){
iLimit=mysize;
jLimit=mysize;
k=0;
while (k < iLimit){
l=0;
while (l < jLimit) {
scanf ("%d",&myA[k][l]);
l=l+1;
}
k=k+1;
}
printMatrix(mysize,mysize,myA);
myC[i][j]=myA[i][k]*myA[k][j];
printf("\n");
printMatrix(mysize,mysize,myC);
return 0;
}
Upvotes: 0
Views: 200
Reputation: 12270
the multiplication of the matrices has to be done for all the elements. so it should be in a nested for loop. what you are doing in your code
myC[i][j]=myA[i][k]*myA[k][j];
this statement would multiply only one element of the matrix that is represented by the index i,j,k
(out of bound in your code). the above statement has to be kept inside 3 nested for loops. something like this..
for (i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
myC[i][j]=0;
for(k=0;k<n;k++)
myC[i][j]+= myA[i][k]*myA[k][j];
}
}
Upvotes: 2
Reputation: 19484
This only multiplies two elements, where i j and k are all out of bounds.
myC[i][j]=myA[i][k]*myA[k][j];
It should be in a triple-loop, where you set i j and k appropriately.
Upvotes: 1