RUN
C C++ JAVA PYTHON SQL HTML CSS DSA Robotics AWS SDE PREPARATION

Made with  & Code

# Java program to subtract two matrices

Written By -

Here, we are supposed to enter two 2D arrays or rather Matrices. The 2D-arrays will be dynamic arrays of identical size (R*C). After entering into the arrays, we’ll have to calculate and print the Difference Matrix (Result After Subtraction of Second Matrix from First Matrix) and along with displaying both the original matrices.

The basic idea to be kept in mind is:
Two matrices can only be subtracted if they are of identical dimensions.

The standard algorithm will be:

1. Enter the size of the two 2D-arrays.
2. Create the two matrices of the input sizes.
3. Using a loop construct, enter integer inputs in both the matrices.
4. Declare another matrix that will store the difference of the original matrices. The size will be (R*C).
5. Using loop construct, subtract both the original matrices and store the result in difference matrix.
6. After the loop terminates, print the result accordingly.

### Source Code:

``````/* Program to enter two 2D arrays and print the difference matrix */

import java.util.*;
class SubtractMatrix
{
public static void main()
{
Scanner inp=new Scanner(System.in);
int r,c,i,j;

System.out.print("\n Enter Dimensions of Matrix (Row * Column) :\n ");
r=inp.nextInt();
c=inp.nextInt();

int a[][]=new int[r][c];     //Creating Matrices of size r*c
int b[][]=new int[r][c];

System.out.println("Enter into First Matrix: ");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
System.out.print("\n Enter: ");
a[i][j]=inp.nextInt();
}
}

System.out.println("Enter into Second Matrix: ");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
System.out.print("\n Enter: ");
b[i][j]=inp.nextInt();
}
}

int diff[][]=new int[r][c];
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
diff[i][j]=a[i][j]-b[i][j];     //Calculating difference of corresponding elements in both matrix
}
}

System.out.println();
System.out.println("First Matrix: ");    // Displaying Result
display(a,r,c);
System.out.println("Second Matrix: ");
display(b,r,c);   //Function to display matrix when invoked.
System.out.println("Resultant Matrix after Subtraction: ");
display(diff,r,c);
}

public static void display(int arr[][],int row,int col)
{
int i,j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}

}``````

### Output:

``````Enter Dimensions of Matrix (Row * Column) :
2
2

Enter into First Matrix:
Enter: 10
Enter: 46
Enter: 63
Enter: 98

Enter into Second Matrix:
Enter: 54
Enter: 23
Enter: 15
Enter: 46

First Matrix:
10 46
63 98

Second Matrix:
54 23
15 46

Resultant Matrix after Subtraction:
-44 23
48 52``````