Java program to Subtract two Matrices

Write a Java program to Subtract two Matrices with an example or perform subtraction on two multidimensional arrays.

In this Subtract two Matrices example, we declared two matrixes. Next, we used the For Loop to iterate those values. We performed multiplication on x and y matrixes within that loop and assigned it to another one called multi. Later, we used another for loop to print the final output.

public class SubtractTwoMatrix {

	public static void main(String[] args) {
		int[][] x = {{10, 12, 3}, {44, 25, 9}, {22, 8, 9}};
		int[][] y = {{ 5, 6, 7}, {8, 9,10}, {2, 35, 4}};
		
		int[][] sub = new int[3][3];
		int i, j;
		
		for(i = 0; i < x.length; i++)
		{
			for(j = 0; j < x[0].length; j++)
			{
				sub[i][j] = x[i][j] - y[i][j];
			}
		}
		System.out.println("------ The Subtraction Matrix Y from Matrix X -----");
		
		for(i = 0; i < x.length; i++)
		{
			for(j = 0; j < x[0].length; j++)
			{
				System.out.format("%d \t", sub[I][j]);
			}
			System.out.println("");
		}
	}
}
Java program to Subtract two Matrices 1

Java program to Subtract two Matrices example

This Java program is the same as above. However, this code allows the user to enter the rows, columns of the matrix, and items. Refer to for loop.

import java.util.Scanner;

public class Example {
	private static Scanner sc;
	public static void main(String[] args) {
		int i, j, rows, columns;
		
		sc= new Scanner(System.in);
		
		System.out.println("\n Enter the Rows & Columns :  ");
		rows = sc.nextInt();
		columns = sc.nextInt();
		
		int[][] arr1 = new int[rows][columns];
		int[][] arr2 = new int[rows][columns];
		
		System.out.println("\n Enter the First Items :  ");
		for(i = 0; i < rows; i++) {
			for(j = 0; j < columns; j++) {
				arr1[i][j] = sc.nextInt();
			}		
		}
		System.out.println("\n Enter the Second Items :  ");
		for(i = 0; i < rows; i++) {
			for(j = 0; j < columns; j++) {
				arr2[i][j] = sc.nextInt();
			}		
		}
		System.out.println("------ The Subtraction Matrix arr2 from arr1 -----");
		for(i = 0; i < rows; i++) {
			for(j = 0; j < columns; j++) {
				System.out.format("%d \t", (arr1[i][j] - arr2[i][j]));
			}
			System.out.println("");
		}
	}
}
 Enter the Rows & Columns :  
3 3

 Enter the First Items :  
10 20 30
40 50 60
70 80 90

 Enter the Second Items :  
5 35 65
9 22 95
90 65 200
------ The Subtraction Matrix arr2 from arr1 -----
5 	-15 	-35 	
31 	28 	-35 	
-20 	15 	-110