In this post, we will see how to subtract two matrices in java.I am giving example for 33 matrix. You can extend it to nn matrices.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
import java.util.Scanner; public class MatrixOperator { public static void main(String args[]) { int i, j; int mat1[][] = new int[3][3]; int mat2[][] = new int[3][3]; int res[][] = new int[3][3]; Scanner scanner = new Scanner(System.in); System.out.print("Enter Matrix 1 Elements : "); for(i=0; i<3; i++){ for(j=0; j<3; j++){ mat1[i][j] = scanner.nextInt(); } } System.out.print("Enter Matrix 2 Elements : "); for(i=0; i<3; i++){ for(j=0; j<3; j++){ mat2[i][j] = scanner.nextInt(); } } for(i=0; i<3; i++){ for(j=0; j<3; j++){ res[i][j] = mat1[i][j] - mat2[i][j]; } } System.out.println("New Matrix is : "); for(i=0; i<3; i++){ for(j=0; j<3; j++){ System.out.print(res[i][j]+ " "); } System.out.println(); } } } |
Output:
Enter Matrix 1 Elements : 11 22 33 44 55 66 77 88 99
Enter Matrix 2 Elements : 10 20 30 40 50 60 70 80 90
New Matrix is :
1 2 3
4 5 6
7 8 9
Enter Matrix 2 Elements : 10 20 30 40 50 60 70 80 90
New Matrix is :
1 2 3
4 5 6
7 8 9
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.