Untitled

 avatar
unknown
plain_text
a year ago
1.1 kB
5
Indexable
public class MatrixSum {
    public static void main(String[] args) {
        // Define matrices
        int[][] matrix1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        int[][] matrix2 = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};

        // Find the sum of matrices
        int[][] sumMatrix = new int[matrix1.length][matrix1[0].length];
        for (int i = 0; i < matrix1.length; i++) {
            for (int j = 0; j < matrix1[0].length; j++) {
                sumMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
            }
        }

        // Display Matrix 1
        System.out.println("Matrix 1:");
        displayMatrix(matrix1);

        // Display Matrix 2
        System.out.println("\nMatrix 2:");
        displayMatrix(matrix2);

        // Display Sum Matrix
        System.out.println("\nSum Matrix:");
        displayMatrix(sumMatrix);
    }

    // Method to display a matrix
    private static void displayMatrix(int[][] matrix) {
        for (int[] row : matrix) {
            for (int value : row) {
                System.out.print(value + " ");
            }
            System.out.println();
        }
    }
}
Editor is loading...
Leave a Comment