# Java Program to Subtract Two Matrices

## 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[0][0] - mat2[0][0], mat1[1][1] - mat2[1][1], and so on. Store the subtraction result in the third matrix say mat3[0][0], mat3[1][1], and so on.

## Java Programming Code to Subtract Two Matrices

Following Java Program ask to the user to enter the two 3*3 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[ ][ ] :

```/* Java Program Example - Subtract Two Matrices */

import java.util.Scanner;

public class JavaProgram
{
public static void main(String args[])
{
int i, j;
int mat1[][] = new int[3][3];
int mat2[][] = new int[3][3];
int mat3[][] = new int[3][3];
Scanner scan = new Scanner(System.in);

System.out.print("Enter Matrix 1 Elements : ");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
mat1[i][j] = scan.nextInt();
}
}

System.out.print("Enter Matrix 2 Elements : ");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
mat2[i][j] = scan.nextInt();
}
}

System.out.print("Subtracting Matrices (i.e. Matrix1 - Matrix2)...\n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
mat3[i][j] = mat1[i][j] - mat2[i][j];
}
}

System.out.print("Result of Matrix1 - Matrix2 is :\n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
System.out.print(mat3[i][j]+ " ");
}
System.out.println();
}
}
}```

When the above Java Program is compile and executed, it will produce the following output:

### Same Program in Other Languages

You may also like to learn and practice the same program in other popular programming languages:

Tools
Calculator