#include <iostream.h>
#include <conio.h>
int main(void)
{
constint N=3;
int A[N][N];
int B[N][N];
int C[N][N];
int i;
int j;
int k;
int sum;
//Here we ask numbers for A
for (i = 0; i < N; i++){
for (j = 0; j < N; j++){
cout << "Type number: ";
cin >> A[i][j];
cout << endl;
}
}
//Here we ask numbers for B
cout << endl << endl;
for (i = 0; i < N; i++){
for (j = 0; j < N; j++){
cout << "Type number: ";
cin >> B[i][j];
cout << endl;
}
}
//Here we calculate C
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
{
sum = 0;
for (k = 0; k < N; k++)
{
sum += A[i][k] * B[k][j];
}
C[i][j] = sum;
}
}
//Here we cout sum
cout << endl << sum;
getch();
return 0;
}
The code is correct but are some difficulties to enter the elements of the matrices.
The program must output C[][], doesn't it? Add some appropriate lines and all will be ok.
The code could be simplified between the lines 34 - 46 as follows:
1 2 3 4 5 6 7 8 9 10
//Here we calculate C
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
{
C[i][j] = 0;
for (k = 0; k < N; k++)
C[i][j] += A[i][k] * B[k][j];
}
}
Before multiplying you must check if the no. of columns of the 1st matrix is equal to the no. of rows of the 2nd matrix.
You can still modify you code as:
1 2 3 4 5 6 7 8 9 10 11 12
.
.
.
// check if they can be multiplied
if(no_of_columns_of_first_matrix != no_of_rows_of_second_matrix)
{
cout << "The matrices can't be multiplied!" << endl;
return -1;
}
.
.
.
In case you haven't noticed I suggested it for a general scenario. If you intend to keep the no. of row and columns same in your program, there's obviously no need of the if statement