# Java Matrix Subtraction Example

In this tutorial, you will learn how to find the subtraction of two matrices.

Tutorials

# Java Matrix Subtraction Example

In this tutorial, you will learn how to find the subtraction of two matrices.

## Java Matrix Subtraction Example

In this tutorial, you will learn how to find the subtraction of two matrices.

Not only, addition and multiplication, you can also subtract matrices. Here we are going to calculate the difference between  two matrices of any order. In the given program, firstly we have allowed the user to enter the number of rows and columns to show in matrices and then accept the matrix elements as array elements. We have declared two 2-dimensional array of integer type to store the matrix elements. Now to find the difference, we have performed the following distinctive steps( for loops ):

```for(int i=0;i<C.length;i++)
for(int j=0;j<C[i].length;j++)
```

Example:

```import java.util.*;
class MatrixSubtraction{

public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter Number of rows: ");
int m = input.nextInt();

System.out.print("Enter Number of columns: ");
int n = input.nextInt();
int[][] A = new int[m][n];
int[][] B = new int[m][n];
int[][] C = new int[m][n];
System.out.println("Enter elements for matrix A : ");
for (int i=0 ; i < A.length ; i++)
for (int j=0 ; j < A[i].length ; j++){
A[i][j] = input.nextInt();
}
System.out.println("Enter elements for matrix B : ");
for (int i=0 ; i < B.length ; i++)
for (int j=0 ; j < B[i].length ; j++){
B[i][j] = input.nextInt();
}
System.out.println("Matrix A: ");
for (int i=0 ; i < A.length ; i++)
{ System.out.println();
for (int j=0 ; j < A[i].length ; j++){
System.out.print(A[i][j]+" ");
}
}
System.out.println();
System.out.println("Matrix B: ");
for (int i=0 ; i < B.length ; i++)
{ System.out.println();
for (int j=0 ; j < B[i].length ; j++){
System.out.print(B[i][j]+" ");
}
}
System.out.println();
System.out.println("Subtraction of 2 matrices: ");
for(int i=0;i<C.length;i++){
for(int j=0;j<C[i].length;j++){
C[i][j]=A[i][j]-B[i][j];
System.out.print(C[i][j]+" ");
}
System.out.println();
}
}
}
```

Output:

```Enter Number of rows: 2
Enter Number of columns: 2
Enter elements for matrix A :
1
2
3
4
Enter elements for matrix B :
1
2
3
4
Matrix A:

1 2
3 4
Matrix B:

1 2
3 4
Subtraction of 2 matrices*
0 0
0 0
```