# Write a Java Program for Subtraction of Two Matrices

By | 27.01.2017

## Write a Java Program for Subtract Two Matrices

To subtract two matrices in Java Programming, you have to ask to the user to enter the two matrix, then start subtracting the matrices i.e., subtract matrix second from the matrix first like mat1 – mat2, mat1 – mat2, and so on.

Store the subtraction result in the third matrix say mat3, mat3, and so on.

• Following Java Program ask to the user to enter the two n*n array/matrix elements to subtract them i.e., Array1 – Array2, then display the subtracted array i.e., the mat3[ ][ ] on the screen which is the subtraction result of mat1[ ][ ] – mat2[ ][ ] :

SOURCE CODE ::

```import java.util.Scanner;

public class Subtract_matrices {
public static void main(String args[])
{
int m, n, c,d;
Scanner in = new Scanner(System.in);

System.out.println("Enter the number of rows and columns of matrix");
m = in.nextInt();
n = in.nextInt();

int first[][] = new int[m][n];
int second[][] = new int[m][n];
int subtract[][] = new int[m][n];

System.out.println("Enter the elements of first matrix");

for (  c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
{
System.out.print(c+""+d+" Element : ");
first[c][d] = in.nextInt();
}

System.out.println("Enter the elements of second matrix");

for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
{
System.out.print(c+""+d+" Element : ");
second[c][d] = in.nextInt();
}

//--------Subtract two matrix-----------------------------------

for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
subtract[c][d] = first[c][d] - second[c][d];

System.out.println("Subtraction of entered matrices:-");

for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < n ; d++ )
System.out.print(subtract[c][d]+"\t");

System.out.println();
}
}
}```

OUTPUT ::

```Enter the number of rows and columns of matrix
2
2
Enter the elements of first matrix
00 Element : 1
01 Element : 2
10 Element : 3
11 Element : 4
Enter the elements of second matrix
00 Element : 4
01 Element : 3
10 Element : 2
11 Element : 1
Subtraction of entered matrices:-
-3      -1
1       3```

4 1 vote
Article Rating
Subscribe
Notify of 