Home >>Java Programs >Java Program to subtract the two matrices
In this example, we will create a java program to get the result of subtraction of two matrices.
Two matrices can be subtracted if and only if they have same dimensions that means the number of rows and columns should be same. It is not possible to subtract a 2 × 3 matrix from a 3 × 2 matrix.
public class Main
{
public static void main(String[] args)
{
int rows, cols;
int a[][] = {
{4, 5, 5},
{8, 4, 3},
{1, 4, 3}
};
int b[][] = {
{2, 2, 6},
{1, 3, 4},
{1, 5, 1}
};
rows = a.length;
cols = a[0].length;
int diff[][] = new int[rows][cols];
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
diff[i][j] = a[i][j] - b[i][j];
}
}
System.out.println("Subtraction of two matrices: ");
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
System.out.print(diff[i][j] + " ");
}
System.out.println();
}
}
}