Q:

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

belongs to collection: Java Array Programs

0

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

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to subtract two matrices in java

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 

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Array Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to check sparse matrix... >>
<< Java program to multiply two matrices...