Java program to add two matrix using multi dimensional arrays

https:‮i.www//‬giftidea.com

Here's an example Java program that demonstrates how to add two matrices using multi-dimensional arrays:

public class MatrixAdditionExample {
    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[][] sum = addMatrices(matrix1, matrix2);

        // print the sum of the matrices
        for (int i = 0; i < sum.length; i++) {
            for (int j = 0; j < sum[0].length; j++) {
                System.out.print(sum[i][j] + " ");
            }
            System.out.println();
        }
    }

    public static int[][] addMatrices(int[][] matrix1, int[][] matrix2) {
        int rows = matrix1.length;
        int columns = matrix1[0].length;
        int[][] sum = new int[rows][columns];

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                sum[i][j] = matrix1[i][j] + matrix2[i][j];
            }
        }

        return sum;
    }
}

In this example, we create two 2D arrays called matrix1 and matrix2 that represent two matrices. We then call the addMatrices() function and pass in the two matrices as arguments. The function adds the corresponding elements of the matrices together and stores the result in a new 2D array called sum.

Finally, we print the contents of the sum array to the console using a nested for loop.

The output of this program will be:

10 10 10
10 10 10
10 10 10