Multiplying two matrices

Hi.
I'm trying to figure out how to multiply two matrices.
Here's my code so far. Is it correct?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream.h>
#include <conio.h>

int main(void) 
 {
     const int 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];
                }
        }

Last edited on
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;
}
.
.
.
Last edited on
to condor:
I simplified the code and added code to output C. :)

to The illusionist mirage:
I improved the code with IF, even though size of columns and rows is fixed "N" = 3.

Thanks for quick answers :)
@Klipeti

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
@Klipeti
You're welcome! Happy programming!
Topic archived. No new replies allowed.