Matrix Addition using Arrays in Java

Exercise:

Write a Java Program to perform matrix addition using multi-dimensional arrays.

Click Here to View the Solution!
public class MatricesAddition {
  
     public static void main(String[] args) {
         int rows = 2, columns = 3;
         int[][] firstMatrix = { {1,6,7}, {3,2,4} };
         int[][] secondMatrix = { {-2,9,0}, {2,4,9} };
  
         // Adding the given two matrices
         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];
             }
         }
         // Displays the result on screen
         System.out.println("Sum of two matrices is: ");
         for(int[] row : sum) {
             for (int column : row) {
                 System.out.print(column + "    ");
             }
             System.out.println();
         }
     }
 } 
Click Here to View the Output!
Sum of two matrices is: 
 -1    15    7    
 5     6    13    
Click Here to View the Explanation!
  • This program depicts the usage of multi-dimensional arrays for addition of two matrices.
  • First Matrix is stored into firstMatrix which possesses two arrays. So is the case with the second matrix which is stored intosecondMatrix.
  • After declaration of elements in the matrices, the number of rows and columns is also declared i.e. 2 and 3 respectively.
  • The first iteration of the for-loop adds the first row elements of firstMatrix corresponding to the first column elements of secondMatrix.
  • The outer loop iterates over rows of the firstMatrix and the inner loop iterates over columns of secondMatrix.
  • Once the first row is added to both columns of the secondMatrix, second row takes it turn and is added to the corresponding elements of secondMatrix.
  • After this both loops break, and the array ‘sum’ that stored each added element during each step, is iterated over using for-each loop to output elements contained in it.
  • Finally the sum of the matrices get printed on console screen.