File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ public class ProdMatrix
2+ {
3+ public static void main (String [] args ) {
4+ int row1 , col1 , row2 , col2 ;
5+ //Initialize matrix a
6+ int a [][] = {
7+ {1 , 3 , 2 },
8+ {3 , 1 , 1 },
9+ {1 , 2 , 2 }
10+ };
11+
12+ //Initialize matrix b
13+ int b [][] = {
14+ {2 , 1 , 1 },
15+ {1 , 0 , 1 },
16+ {1 , 3 , 1 }
17+ };
18+
19+ //Calculates number of rows and columns present in first matrix
20+ row1 = a .length ;
21+ col1 = a [0 ].length ;
22+
23+ //Calculates the number of rows and columns present in the second matrix
24+
25+ row2 = b .length ;
26+ col2 = b [0 ].length ;
27+
28+ //For two matrices to be multiplied,
29+ //number of columns in first matrix must be equal to number of rows in second matrix
30+ if (col1 != row2 ){
31+ System .out .println ("Matrices cannot be multiplied" );
32+ }
33+ else {
34+ //Array prod will hold the result
35+ int prod [][] = new int [row1 ][col2 ];
36+
37+ //Performs product of matrices a and b. Store the result in matrix prod
38+ for (int i = 0 ; i < row1 ; i ++){
39+ for (int j = 0 ; j < col2 ; j ++){
40+ for (int k = 0 ; k < row2 ; k ++){
41+ prod [i ][j ] = prod [i ][j ] + a [i ][k ] * b [k ][j ];
42+ }
43+ }
44+ }
45+
46+ System .out .println ("Product of two matrices: " );
47+ for (int i = 0 ; i < row1 ; i ++){
48+ for (int j = 0 ; j < col2 ; j ++){
49+ System .out .print (prod [i ][j ] + " " );
50+ }
51+ System .out .println ();
52+ }
53+ }
54+ }
55+ }
You can’t perform that action at this time.
0 commit comments