can someone help mi out with how to write a simple(2X2) matrix....I need help only with the loop used..... I got a wrong answer with what i got below

``````const int Row = 2;
const int Col = 2;
int main()
{
int MatrixA[Row][Col] = {1,2,3,2};
int MatrixB[Row][Col] = {1,1,2,1};
int MatrixC[Row][Col] = {0};

for(int i = 0; i < Row ; i++)
{
for(int j = 0; j < Col; j++){
MatrixC[i][j] = (MatrixA[i][j] * MatrixB[i][j]) + (MatrixA[i][j+1] * MatrixB[i+1][j]);
cout<<MatrixC[i][j];
}
cout<<endl;
}

system("PAUSE");
return 0;
}``````

:)

4
Contributors
3
Replies
4
Views
9 Years
Discussion Span
Last Post by ddanbe

You have to check if you have enough room before you use `[i+1], [j+1]` ; because you're going past the your array boundaries.
See how it goes past at [0][2]:

``````MatrixC[0][0] = (MatrixA[0][0] * MatrixB[0][0]) + (MatrixA[0][1] * MatrixB[1][0]);
MatrixC[0][1] = (MatrixA[0][1] * MatrixB[0][1]) + (MatrixA[0][2] * MatrixB[1][1]);``````

Always tree for loops for this to work:

``````for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
for (int k = 0; k < N; k++)
C[i][k] += A[i][j] * B[j][k];``````

and I should read very carefull what MozaicFuneral has to say.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.