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 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
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
- loops in java – https://gangforcode.com/loops-in-java/
- Multidimensional Array in Java – https://gangforcode.com/multidimensional-array-in-java/
- Matrix Addition in Java – https://gangforcode.com/matrix-addition-in-java/
- Binary Search in Java – https://gangforcode.com/binary-search-in-java/
- first non repeating character – https://gangforcode.com/fiirst-non-repeating-character-in-the-string/
- Armstrong number in java – https://gangforcode.com/armstrong-number-in-java/
- All Armstrong Numbers – https://gangforcode.com/all-armstrong-numbers/