Google News
logo
Java Program to Subtract the Two Matrices
In the following examples of Java program to subtract two matrices :
Program :
public class MatrixSubtraction {
    public static void main(String[] args) {
        int[][] matrix1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        int[][] matrix2 = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
        int[][] resultMatrix = subtractMatrices(matrix1, matrix2);

        System.out.println("Matrix 1:");
        printMatrix(matrix1);
        System.out.println("Matrix 2:");
        printMatrix(matrix2);
        System.out.println("Result Matrix:");
        printMatrix(resultMatrix);
    }

    public static int[][] subtractMatrices(int[][] matrix1, int[][] matrix2) {
        int rows1 = matrix1.length;
        int cols1 = matrix1[0].length;

        int[][] result = new int[rows1][cols1];

        for (int i = 0; i < rows1; i++) {
            for (int j = 0; j < cols1; j++) {
                result[i][j] = matrix1[i][j] - matrix2[i][j];
            }
        }

        return result;
    }

    public static void printMatrix(int[][] matrix) {
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}
Output :
Matrix 1:
1 2 3 
4 5 6 
7 8 9 
Matrix 2:
9 8 7 
6 5 4 
3 2 1 
Result Matrix:
-8 -6 -4 
-2 0 2 
4 6 8 
In this program, we have two matrices matrix1 and matrix2, which are subtracted to produce a third matrix resultMatrix. The matrices are represented as two-dimensional arrays.

We define a method subtractMatrices that takes two matrices as input and returns their difference. We first calculate the number of rows and columns of the resulting matrix, which are the same for both matrices.

We then define a new two-dimensional array result with the appropriate size. We use two nested loops to calculate each element of the resulting matrix.

Finally, we define a method printMatrix to print a matrix to the console.