In this Java program, you’ll learn how to Add Two Matrices Using Multi-dimensional Arrays using the Java programming language.
How to Add Two Matrices Using Multi-dimensional Arrays using JAVA?
Example 1: Program to add two Matrices
RUN CODE SNIPPETpublic class Main { public static void main(String[] args) { int rows = 2, columns = 3; int[][] firstMatrix = { {5, 4, 4}, {5, 4, 4} }; int[][] secondMatrix = { {6, 5, 3}, {5, 6, 3} }; int[][] sum = new int[rows][columns]; for(int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { sum[i][j] = firstMatrix[i][j] + secondMatrix[i][j]; } } System.out.println("Sum of two matrices is: "); for(int[] row : sum) { for (int column : row) { System.out.print(column + " "); } System.out.println(); } } }
OUTPUT
Sum of two matrices is: 11 9 7 10 10 7
In the above program, the two arrays are stored in the firstmatrix and secondmatrix. The number of rows and columns are stored in the variables row and columns.
The addition of the given two matrix are stored in the array called sum. To add and store the results loop through each index of the given array