Uploaded by Jessa Gebana

NO.18

advertisement
(paste below "package matrixmultiplication;")
import java.util.Scanner;
(paste at "// TODO code application logic here")
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows (m) of the first matrix: ");
int m = scanner.nextInt();
System.out.print("Enter the number of columns (n) of the first matrix: ");
int n = scanner.nextInt();
System.out.print("Enter the number of columns (p) of the second matrix: ");
int p = scanner.nextInt();
int[][] matrix1 = new int[m][n];
int[][] matrix2 = new int[n][p];
int[][] productMatrix = new int[m][p];
System.out.println("Enter the elements of the first matrix:");
readMatrixElements(scanner, matrix1);
System.out.println("Enter the elements of the second matrix:");
readMatrixElements(scanner, matrix2);
multiplyMatrices(matrix1, matrix2, productMatrix);
System.out.println("Matrix 1:");
displayMatrix(matrix1);
System.out.println("Matrix 2:");
displayMatrix(matrix2);
System.out.println("Product Matrix:");
displayMatrix(productMatrix);
scanner.close();
}
private static void readMatrixElements(Scanner scanner, int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
System.out.print("Enter element at position (" + (i + 1) + ", " + (j + 1) + "): ");
matrix[i][j] = scanner.nextInt();
}
}
}
private static void multiplyMatrices(int[][] matrix1, int[][] matrix2, int[][] productMatrix) {
int m = matrix1.length;
int n = matrix2.length;
int p = matrix2[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < p; j++) {
int sum = 0;
for (int k = 0; k < n; k++) {
sum += matrix1[i][k] * matrix2[k][j];
}
productMatrix[i][j] = sum;
}
}
}
private static void displayMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
System.out.println();
Download