# Java Program to subtract the two matrices

In this program, we need to get the result of subtraction of two matrices.

Two matrices A and B can be subtracted if and only if they have same dimensions that are, the same number of rows and columns. It is not possible to subtract a 2 × 3 matrix from a 3 × 2 matrix. Subtraction of two matrices can be performed by subtracting their corresponding elements as

1. (A – B)<sub>ij</sub>= A<sub>ij</sub> – B<sub>ij</sub>

Subtraction of two matrices can be performed by looping through the first and second matrix. Calculating the difference between their corresponding elements and store the result in the third matrix.

### Algorithm

• STEP 1: START
• STEP 2: DEFINE rows, cols
• STEP 3: INITIALIZE first matrix a[][] ={{4,5,6},{3,4,1}, {1,2,3}}
• STEP 4: INITIALIZE second matrix b[][] ={{2,0,3}, {2,3,1}{1,1,1}}
• STEP 5: rows = a.length
• STEP 6: cols = a.length
• STEP 7: DEFINE diff[][]
• STEP 8: REPEAT STEP 9 to STEP 10 UNTIL i<rows
//for(i=0;i<rows; i++)
• STEP 9: REPEAT STEP 10 UNTIL j<cols
//for(j=0;j<cols; j++)
• STEP 10: diff[i][j] =a[i][j] – b[i][j]
• STEP 11: PRINT “Subtraction of two matrices:”
• STEP 12: REPEAT STEP 13 to STEP 14 UNTIL i<rows
//for(i=0;i<rows; i++)
• STEP 13: REPEAT STEP 14 UNTIL j<cols
//for(j=0; j<cols; j++)
• STEP 13: PRINT diff[i][j]
• STEP 14: PRINT new line
• STEP 15: END

### Program:

1. public class Sub_Matrix
2. {
3.     public static void main(String[] args) {
4.         int rows, cols;
5.
6.         //Initialize matrix a
7.           int a[][] = {
8.                           {4, 5, 6},
9.                           {3, 4, 1},
10.                           {1, 2, 3}
11.                        };
12.
13.           //Initialize matrix b
14.           int b[][] = {
15.                           {2, 0, 3},
16.                          {2, 3, 1},
17.                          {1, 1, 1}
18.                      };
19.
20.           //Calculates number of rows and columns present in given matrix
21.           rows = a.length;
22.         cols = a.length;
23.
24.           //Array diff will hold the result
25.         int diff[][] = new int[rows][cols];
26.
27.         //Performs subtraction of matrices a and b. Store the result in matrix diff
28.         for(int i = 0; i < rows; i++){
29.             for(int j = 0; j < cols; j++){
30.                 diff[i][j] = a[i][j] – b[i][j];
31.             }
32.         }
33.
34.         System.out.println(“Subtraction of two matrices: “);
35.         for(int i = 0; i < rows; i++){
36.             for(int j = 0; j < cols; j++){
37.                System.out.print(diff[i][j] + ” “);
38.             }
39.             System.out.println();
40.         }
41.     }
42. }

Output:

```Subtraction of two matrices:
1	5    3
1    1    0
0    1    2```