Java program to add or sum two matrices with example

  • Given two matrices in Java.
  • Write a program two add matrices.
  • Two matrices can be added only if they have the same dimension.
    • i.e. two matrices must have the same number of rows and columns.
  • Addition is accomplished by adding respective elements of each matrix.

Example to add two matrices in java

Matrix A =    [ {1  2 3}
 
                {4  5 6}
 
                {7 8 9} ]
 
 
Matrix B =      [ {11  12 13}
 
                 {14  15 16}
 
                 {17 18 19} ]
 
 
Sum (A + B) = [ {1+11  2 +12 3+13}
 
                {4+14  5 +15 6+16}
 
                {7+17  8 +18 9+19} ]
 
 
Sum (A + B) = [ {12  14 16 }
 
                {18  20 22}
 
                {24  26 28} ]

Program to add or sum two matrices in Java

package org.learn.beginner.matrices;
 
import java.util.Arrays;
 
public class AddTwoMatrices {
 
    private static void sumOfMatrices(int[][] a, int[][] b) {
 
        System.out.println("Matrix A :" + Arrays.deepToString(a));
        System.out.println("Matrix B :" + Arrays.deepToString(b));
         
        int row = a.length;
        int col = a[0].length;
 
        int[][] sum = new int[row][col];
        int iRow = 0, iCol = 0;
 
        while (iRow < row) {
 
            while (iCol < col) {
                sum[iRow][iCol] = a[iRow][iCol] + b[iRow][iCol];
                iCol++;
            }
            iCol = 0;
            iRow++;
        }
 
        System.out.println("Sum (A+B) :" + Arrays.deepToString(sum));
    }
 
    public static void main(String[] args) {
        int[][] A = {{1, 2, 3},
 
                    {4, 5, 6},
 
                    {7, 8, 9}};
 
        int[][] B = {{11, 12, 13},
 
                    {14, 15, 16},
 
                    {17, 18, 19}};
 
        sumOfMatrices(A, B);
    }
}

Output: Sum of two matrices in Java

Matrix A :[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Matrix B :[[11, 12, 13], [14, 15, 16], [17, 18, 19]]
Sum (A+B) :[[12, 14, 16], [18, 20, 22], [24, 26, 28]]