Java Matrix Subtraction
Chapter:
Math Class
Last Updated:
18-05-2017 13:18:30 UTC
Program:
/* ............... START ............... */
import java.util.Scanner;
public class JavaMatrixSubtraction {
public static void main(String args[]) {
int rows, columns, c, d;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of matrix");
rows = in.nextInt();
columns = in.nextInt();
int matrix1[][] = new int[rows][columns];
int matrix2[][] = new int[rows][columns];
int diff[][] = new int[rows][columns];
System.out.println("Enter the elements of matrix1");
for (c = 0; c < rows; c++) {
for (d = 0; d < columns; d++) {
matrix1[c][d] = in.nextInt();
}
}
System.out.println("Enter the elements of matrix2");
for (c = 0; c < rows; c++) {
for (d = 0; d < columns; d++) {
matrix2[c][d] = in.nextInt();
}
}
for (c = 0; c < rows; c++) {
for (d = 0; d < columns; d++) {
diff[c][d] = matrix1[c][d] - matrix2[c][d];
}
}
System.out.println("Difference of entered matrices:-");
for (c = 0; c < rows; c++) {
for (d = 0; d < columns; d++) {
System.out.print(diff[c][d] + "\t");
}
System.out.println();
}
}
}
/* ............... END ............... */
Output
Enter the number of rows and columns of matrix
2
2
Enter the elements of matrix1
1
3
5
6
Enter the elements of matrix2
4
5
6
7
Difference of entered matrices:-
-3 -2
-1 -1
Notes:
-
Matrix subtraction is the operation of subtracting two matrices by subtracting the corresponding entries together. Two matrices must have an equal number of rows and columns to be subtracted.
Tags
Matrix Subtraction, Java, Math