Java Program to Add Two Matrix Using Multi-dimensional Arrays

In this program, you’ll learn to add two matrices using multi-dimensional arrays in Java.

 

Example: Program to Add Two Matrices

  1. public class AddMatrices {
  2. public static void main(String[] args) {
  3. int rows = 2, columns = 3;
  4. int[][] firstMatrix = { {2, 3, 4}, {5, 2, 3} };
  5. int[][] secondMatrix = { {-4, 5, 3}, {5, 6, 3} };
  6. // Adding Two matrices
  7. int[][] sum = new int[rows][columns];
  8. for(int i = 0; i < rows; i++) {
  9. for (int j = 0; j < columns; j++) {
  10. sum[i][j] = firstMatrix[i][j] + secondMatrix[i][j];
  11. }
  12. }
  13. // Displaying the result
  14. System.out.println("Sum of two matrices is: ");
  15. for(int[] row : sum) {
  16. for (int column : row) {
  17. System.out.print(column + " ");
  18. }
  19. System.out.println();
  20. }
  21. }
  22. }

When you run the program, the output will be:

Sum of two matrices is:
-2    8    7    
10    8    6    

In the above program, the two matrices are stored in 2d array, namely firstMatrix and secondMatrix. We’ve also defined the number of rows and columns and stored them in variables rows and columns respectively.

Then, we initialize a new array of the given rows and columns called sum. This matrix array stores the addition of the given matrices.

We loop through each index of both arrays to add and store the result.

Finally, we loop through each element in the sum array using a for (foreach variation) loop to print the elements.