Java program to subtract two matrices (subtraction of two matrices)

In this java program, we are going to read two matrices and finding their multiplication in third matrix and printing the resultant matrix. By IncludeHelp Last updated : December 23, 2023

Problem statement

Given two matrices, we have to find and print their subtraction using Java program.

Example

Input (Matrix 1)
55 66
99 88

Input (Matrix 2)
44 55
88 77

Output (Subtracted Matrix)
11 11 
11 11

Java program to subtract two matrices

import java.util.Scanner;

public class MatrixSubtraction {
  public static void main(String args[]) {
    int n, i, j;
    //scanner class object 
    Scanner scan = new Scanner(System.in);

    //input total number of rows and cols (i.e. base for both)
    System.out.print("Enter the base of the matrices : ");
    n = scan.nextInt();

    //matrix (two_d array) object declarations
    int mat1[][] = new int[n][n];
    int mat2[][] = new int[n][n];
    int mat3[][] = new int[n][n];

    //input matrix 1
    System.out.println("Enter the elements of the first matrix : ");
    for (i = 0; i < n; i++) {
      for (j = 0; j < n; j++) {
        mat1[i][j] = scan.nextInt();
      }
    }

    //input matrix 2
    System.out.println("Enter the elements of the second matrix : ");
    for (i = 0; i < n; i++) {
      for (j = 0; j < n; j++) {
        mat2[i][j] = scan.nextInt();
      }
    }

    //subtracting matrices 
    System.out.println("Subtracting Matrices --Matrix1 - Matrix2--");
    for (i = 0; i < n; i++) {
      for (j = 0; j < n; j++) {
        mat3[i][j] = mat1[i][j] - mat2[i][j];
      }
    }

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

Output 1

Enter the base of the matrices : 3
Enter the elements of the first matrix : 
6 7 8
9 8 7
6 7 8
Enter the elements of the second matrix : 
6 6 8
8 8 6
6 6 8
Subtracting Matrices --Matrix1 - Matrix2--
Result of Matrix1 - Matrix2 is : 
0 1 0 
1 0 1 
0 1 0

Output 2

Enter the base of the matrices : 2
Enter the elements of the first matrix : 
55 66
99 88
Enter the elements of the second matrix : 
44 55
88 77
Subtracting Matrices --Matrix1 - Matrix2--
Result of Matrix1 - Matrix2 is : 
11 11 
11 11 

Java Array Programs »

More Java Array Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.