Subtraction of Two Matrices
This program subtracts one matrix from another element wise.
Problem Statement
Write a Java program to subtract matrix B from matrix A (3x3).
Source Code
| 1 | public class MatrixSubtraction { |
| 2 | public static void main(String[] args) { |
| 3 | int[][] A = {{5,6,7},{8,9,10},{11,12,13}}; |
| 4 | int[][] B = {{1,2,3},{4,5,6},{7,8,9}}; |
| 5 | int[][] C = new int[3][3]; |
| 6 | for(int i=0;i<3;i++){ |
| 7 | for(int j=0;j<3;j++){ |
| 8 | C[i][j] = A[i][j] - B[i][j]; |
| 9 | } |
| 10 | } |
| 11 | for(int i=0;i<3;i++){ |
| 12 | for(int j=0;j<3;j++){ |
| 13 | System.out.print(C[i][j]+" "); |
| 14 | } |
| 15 | System.out.println(); |
| 16 | } |
| 17 | } |
| 18 | } |
Program Output
4 4 4 4 4 4 4 4 4
Explanation
Two matrices A and B are initialized, and a result matrix C of the same dimensions is filled by nested loops that subtract corresponding elements, demonstrating matrix subtraction and arithmetic operations on multidimensional arrays.