Java Program to subtract two matrices
Program
import java.util.Scanner;
class SubtractMatrix
{
public static void main(String[] args) {
int i, j;
int row, col;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows for both matrix:\t");
row = sc.nextInt();
System.out.println("Enter the number of columns for both matrix:\t");
col = sc.nextInt();
int mat1[][] = new int[row][col];
int mat2[][] = new int[row][col];
int mat3[][] = new int[row][col];
System.out.printf("Enter %d elements for matrix 1\n", row * col);
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
mat1[i][j] = sc.nextInt();
}
}
System.out.printf("Enter %d elements for matrix 2\n", row * col);
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
mat2[i][j] = sc.nextInt();
}
}
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
mat3[i][j] = mat1[i][j] - mat2[i][j];
}
}
System.out.println("The Subtract of two Matrices is:\n");
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
System.out.printf("%d\t", mat3[i][j]);
}
System.out.println("\n");
}
}
}
Output
$ javac SubtractMatrix.java
$ java SubtractMatrix
Enter the number of rows for both matrix:
3
Enter the number of columns for both matrix:
3
Enter 9 elements for matrix 1
34
22
12
86
74
32
45
65
71
Enter 9 elements for matrix 2
99
15
78
85
36
63
45
58
11
The Subtract of two Matrices is:
-65 7 -66
1 38 -31
0 7 60