Java 2D Array Matrix Multiplication
What is the output of the matrix multiplication program above?
public class MatrixMultiply {
public static int[][] multiply(int[][] a, int[][] b) {
int rows = a.length;
int cols = b[0].length;
int sumLength = a[0].length;
int[][] product = new int[rows][cols];
for (int i = 0; i < rows; i++){
for (int j = 0; j < cols; j++){
int sum = 0;
for (int k = 0; k < sumLength; k++){
sum += a[i][k] * b[k][j];
}
product[i][j] = sum;
}
}
return product;
}
public static void main(String[] args){
int[][] A = { {1,2,3}, {4,5,6} };
int[][] B = { {7,8}, {9,10}, {11,12} };
int[][] C = multiply(A, B);
for (int[] row : C){
for (int n : row)
System.out.print(n + " ");
System.out.println();
}
}
}
A
58 139 (newline) 64 154
B
58 64 (newline) 139 154
C
A runtime error due to mismatched dimensions
D
Compilation error due to incorrect index usage
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE