Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to Substract two matrix .

Java Code Example — Array Programs

ADVERTISEMENT

Java Program to Substract two matrix .

Objective

Write a Java program to subtract two matrices.

Algorithm / Approach

  1. Declare three 3x3 matrices: m1, m2, and m3.
  2. Use a Scanner and nested loops to populate m1 and m2 from user input.
  3. Use nested loops to subtract corresponding elements: m3[i][j] = m1[i][j] - m2[i][j].
  4. Format and print the m3 matrix.
Matrix.java
import java.util.Scanner;
class Matrix {
 void sub() {
  Scanner s=new Scanner(System.in);
  int m1[][] = new int[3][3];
  int m2[][] = new int[3][3];
  int m3[][] = new int[3][3];
  System.out.println("Enter Elements of Mat1: ");
  for(int i = 0; i< 3; i++) {
   for(int j = 0; j< 3; j++) { 
    m1[i][j] = s.nextInt();
   }
  }
  System.out.println("Enter Elements of Mat2: ");
  for(int i = 0; i< 3; i++) {
   for(int j = 0; j< 3; j++) { 
    m2[i][j] = s.nextInt();
   }
  }
  System.out.println("Difference of the matrix: ");
  for(int i = 0; i< 3; i++) {
   for(int j = 0; j< 3; j++) { 
    m3[i][j] = m1[i][j]-m2[i][j];
    System.out.print(m3[i][j]+"  ");
   }
   System.out.println();
  }
 }
 public static void main(String[] a)
 {
  Matrix m = new Matrix();
  m.sub();
 }
}

Expected Output

Enter Elements of Mat1:
6 7 8
8 7 6
5 6 8
Enter Elements of Mat2:
4 5 6
3 4 4
3 4 2
Difference of the matrix:
2  2  2
5  3  2
2  2  6

Explanation of the Program

  • Matrix subtraction follows the exact same mechanical process as matrix addition.
  • The nested loops iterate over the exact same (i, j) coordinates for both matrices simultaneously.
  • The only difference is the mathematical operator applied during the assignment to the result matrix.

Complexity

Time Complexity O(r * c)
Space Complexity O(r * c)
ADVERTISEMENT