import java.util.Scanner;
public class MatrixSubtraction {
public static void main(String args[]) {
int n, i, j;
//scanner class object
Scanner scan = new Scanner(System.in);
//input total number of rows and cols (i.e. base for both)
System.out.print("Enter the base of the matrices : ");
n = scan.nextInt();
//matrix (two_d array) object declarations
int mat1[][] = new int[n][n];
int mat2[][] = new int[n][n];
int mat3[][] = new int[n][n];
//input matrix 1
System.out.println("Enter the elements of the first matrix : ");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
mat1[i][j] = scan.nextInt();
}
}
//input matrix 2
System.out.println("Enter the elements of the second matrix : ");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
mat2[i][j] = scan.nextInt();
}
}
//subtracting matrices
System.out.println("Subtracting Matrices --Matrix1 - Matrix2--");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
mat3[i][j] = mat1[i][j] - mat2[i][j];
}
}
//printing final matrix
System.out.println("Result of Matrix1 - Matrix2 is : ");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
System.out.print(mat3[i][j] + " ");
}
System.out.println();
}
}
}
Output 1
Enter the base of the matrices : 3
Enter the elements of the first matrix :
6 7 8
9 8 7
6 7 8
Enter the elements of the second matrix :
6 6 8
8 8 6
6 6 8
Subtracting Matrices --Matrix1 - Matrix2--
Result of Matrix1 - Matrix2 is :
0 1 0
1 0 1
0 1 0
Output 2
Enter the base of the matrices : 2
Enter the elements of the first matrix :
55 66
99 88
Enter the elements of the second matrix :
44 55
88 77
Subtracting Matrices --Matrix1 - Matrix2--
Result of Matrix1 - Matrix2 is :
11 11
11 11
Program to subtract two matrices in java
Output 1
Output 2