Java Program for the Subtraction of Two Matrices

This tutorial shows how to subtract two matrices in Java. As this program is based on Array and uses of for loop so you may go through the following first.

Matrices mean having two-dimension that is there are columns and rows in the following java example.

The Program takes the input for both the column and row elements from the user using the scanner class and a third two-dimensional array is created to store the subtraction result of two matrices. And lastly displays the final result.


Java Program to Subtract Two Matrices

  //subtraction of matrices in java

  import java.util.Scanner;

  public class SubtractionMatrix
  {
    public static void main(String args[])
    {
      int row, col, i, j;
      Scanner sc = new Scanner(System.in);

      System.out.println("Enter the number of rows");
      row = sc.nextInt();

      System.out.println("Enter the number  columns");
      col = sc.nextInt();

      int mat1[][] = new int[row][col];
      int mat2[][] = new int[row][col];
      int result[][] = new int[row][col];

      //First matrix Input
      System.out.println("Enter the elements of matrix1");
      for (i = 0; i < row; i++)
      {

        for (j = 0; j < col; j++)
          mat1[i][j] = sc.nextInt();
      }

      //Second matrix Input
      System.out.println("Enter the elements of  matrix2");
      for (i = 0; i < row; i++)
      {

        for (j = 0; j < col; j++)
          mat2[i][j] = sc.nextInt();
      }

      //Subtraction
      for (i = 0; i < row; i++)
        for (j = 0; j < col; j++)
          result[i][j] = mat1[i][j] - mat2[i][j];

      System.out.println("Result of subtraction:-");

      for (i = 0; i < row; i++)
      {
        for (j = 0; j < col; j++)
          System.out.print(result[i][j] + "\t");

        System.out.println();
      }
    }
  }

Output:

 Enter the number of rows
 3
 Enter the number  columns
 2
 Enter the elements of matrix1
 4
 6
 8
 1
 2
 6
 Enter the elements of  matrix2
 0
 0
 0
 0
 0
 0
 Result of subtraction:-
 4	 6	
 8	 1	
 2	 6