MIT-Curricular/OOP/Java/Lab/Week4/MatrixMulp.java

75 lines
2.1 KiB
Java
Raw Normal View History

2024-08-31 01:24:00 +05:30
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();
}
}
// Adding matrices
System.out.println("Result of addition:");
2024-08-31 01:24:00 +05:30
if (m == p && n == q) {
int C[][] = new int[m][n];
2024-08-31 01:24:00 +05:30
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.print(C[i][j] + " ");
2024-08-31 01:24:00 +05:30
}
System.out.println();
2024-08-31 01:24:00 +05:30
}
}
// Multiplying matrices
System.out.println("Result of multiplication:");
2024-08-31 01:24:00 +05:30
if (n == p) {
int D[][] = new int[m][q];
2024-08-31 01:24:00 +05:30
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.print(D[i][j] + " ");
2024-08-31 01:24:00 +05:30
}
System.out.println();
2024-08-31 01:24:00 +05:30
}
}
}
}