Matrix Subtraction – Java program for subtracting two matrices

In this article, we are going to write a java program to subtract two matrices.

Matrix Subtraction Conditions

For performing matrix subtraction the row and column should be equal in both matrices. We can not perform matrix subtraction if the no of columns and rows is not the same in both matrices.

Matrix Subtraction Example

matrix subtraction

Matrix Subtraction Code

Steps

  • Take input for both matrix
  • Subtract both matrix
  • Print Result matrix

Matrix Subtraction – Java Code

package gangforcode;
import java.util.*;
public class matrix_subtraction {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter the size of array(n*n)");
		int n=sc.nextInt();
		int[][] matrix1=new int [n][n];
		int[][] matrix2 = new int[n][n];
		System.out.println("Enter the first matrix");
		for(int i=0;i<n;i++) {
			for(int j=0;j<n;j++) {
				matrix1[i][j]=sc.nextInt();
			}
		}
		System.out.println("Enter the second array");
		for(int i=0;i<n;i++) {
			for(int j=0;j<n;j++) {
				matrix2[i][j]=sc.nextInt();
			}
		}
        int [][] sub=new int[n][n];
        for(int i=0;i<n;i++) {
        	for(int j=0;j<n;j++) {
        		sub[i][j]=matrix1[i][j]- matrix2[i][j];
        		}
        	}
           System.out.println("Result after subtraction");
           for(int i=0;i<n;i++) {
        	   for(int j=0;j<n;j++) {
        		   System.out.print(sub[i][j]+ " ");
        	   }
        	   System.out.println();
           }
           
	}

}

Output

Matrix Subtraction

Here we are subtracting two square matrices using java. You can also subtract two matrices in C, C++, Python, and other programming languages.

Similar Java Tutorial

Leave a Comment