import java.util.Scanner; class MatrixMulp { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println( "Enter the number of rows and columns in the matrix A: " ); int m = sc.nextInt(); int n = sc.nextInt(); System.out.println( "Enter the number of rows and columns in the matrix B: " ); int p = sc.nextInt(); int q = sc.nextInt(); System.out.println( "Matrices are " + ((m == p && n == q) ? "" : "not ") + "compatible for addition." ); System.out.println( "Matrices are " + ((n == p) ? "" : "not ") + "compatible for multiplication." ); int[][] A = new int[m][n]; int[][] B = new int[p][q]; System.out.println("Enter the elements of matrix A:"); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { A[i][j] = sc.nextInt(); } } System.out.println("Enter the elements of matrix B:"); for (int i = 0; i < p; i++) { for (int j = 0; j < q; j++) { B[i][j] = sc.nextInt(); } } if (m == p && n == q) { int[][] C = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { C[i][j] = A[i][j] + B[i][j]; } } System.out.println("Result of addition:"); printMatrix(C); } if (n == p) { int[][] D = new int[m][q]; for (int i = 0; i < m; i++) { for (int j = 0; j < q; j++) { for (int k = 0; k < n; k++) { D[i][j] += A[i][k] * B[k][j]; } } } System.out.println("Result of multiplication:"); printMatrix(D); } } }