Matrix Addition in Java

Matrix Addition in Java | Addition of two matrix in Java | Java program to add two matrices | Add two matrix in Java | In this post, we will see the Java program to find the matrix addition in Java.

Problem Statement:- Write a Java program to accept two square matrices, store them in an array, add the matrices and display the result. Use classes and methods.

Let A =[aij] and B =[bij] be m × n matrices. The sum of A and B, denoted by A + B, is the m × n matrix that has aij + bij as its (i, j)th element. In other words, A + B =[aij + bij].

The sum of two matrices of the same size is obtained by adding elements in the corresponding positions.

Condition for matrix addition:- Both matrices should have the same row and column size.

Matrices of different sizes cannot be added, because the sum of two matrices is defined only when both matrices have the same number of rows and the same number of columns.

     a11  a12
A = 
     a21  a22
     b11  b12
B = 
     b21  b22

The addition of A and B can be calculated as,

        a11+b11  a12+b12
A + B =
a21+b21 a22+b22

Java Method to find the sum of two matrices

// method to calculate the addition of two matrix
public static int[][] addMatrix(int[][] a, int[][] b) {

   // calculate row and column size of anyone matrix
   int row = a.length;
   int column = a[0].length;
    
   // declare a matrix to store resultant value
   int sum[][] = new int[row][column];
    
   // calculate sum of two matrices
   // outer loop for row
   for(int i=0; i<row; i++) {

     // inner loop for column
     for(int j=0; j<column; j++) {
     
       // formula
       sum[i][j] = a[i][j] + b[i][j];
     }
   }
    
   // return resultant matrix
   return sum;
}

Time Complexity:- O(N2)

The above Java method uses two loops to find the matrix addition therefore the time complexity for the method is O(N2).

Program for Matrix Addition in Java

In this program, values for the matrices are already given just call the method to add both matrices, and then display the resultant matrix.

import java.util.Arrays;

public class Matrix {

  // main method
  public static void main(String[] args) {

    // declare and initialize two matrices
    int a[][] = { { 1, 3 }, { 7, 5 } };
    int b[][] = { { 6, 8 }, { 4, 2 } };

    // find row and column size
    // (Assuming both matrix have same size)
    int row = a.length;
    int column = a[0].length;

    // declare new matrix to store result
    int c[][] = new int[row][column];

    // sum of matrix
    c = addMatrix(a, b);

    // display all matrices
    System.out.println("A = " + Arrays.deepToString(a));
    System.out.println("B = " + Arrays.deepToString(b));
    System.out.println("C = " + Arrays.deepToString(c));
  }
  
  // method to calculate the addition of two matrix
  public static int[][] addMatrix(int[][] a, int[][] b) {

    // calculate row and column size
    int row = a.length;
    int column = a[0].length;
    
    // declare a matrix to store resultant
    int sum[][] = new int[row][column];
    
    // calculate sum of two matrices
    // outer loop for row
    for(int i=0; i<row; i++) {
      // inner loop for column
      for(int j=0; j<column; j++) {
        // formula
        sum[i][j] = a[i][j] + b[i][j];
      }
    }
    
    // return resultant matrix
    return sum;
  }
}

Output:-

A = [[1, 3], [7, 5]]
B = [[6, 8], [4, 2]]
C = [[7, 11], [11, 7]]

In this program, to display the matrix we had used deepToString() method of the Arrays class, but you can also use the nested loops. See:- Different ways to print array in Java

Program by taking Input from the User

In the above program both matrices A and B were initialized within the program, now let us see another Java program for matrix addition by taking input value from the user using Scanner. If you want then you can also use BufferedReader class.

import java.util.Scanner;

public class Matrix {
  
  // create Scanner class object to read input
  private static Scanner scan = new Scanner(System.in);

  // main method
  public static void main(String[] args) {
    
    // declare variables
    int row = 0;
    int column = 0;
    int a[][] = null; // first matrix
    int b[][] = null; // second matrix
    int c[][] = null; // resultant matrix
    
    // ask row and column size
    System.out.println("Enter row and column size: ");
    row = scan.nextInt();
    column = scan.nextInt();

    // initialize matrices
    a = new int[row][column];
    b = new int[row][column];
    c = new int[row][column];
    
    // read matrix A and B
    System.out.println("Enter Matrix A: ");
    a = readMatrix(a);
    System.out.println("Enter Matrix B: ");
    b = readMatrix(b);

    // sum of matrix
    c = addMatrix(a, b);

    // display resultant matrix
    System.out.println("Sum (C): ");
    for(int i=0; i<c.length; i++) {
      for(int j=0; j<c[0].length; j++) {
        System.out.print(c[i][j]+" ");
      }
      System.out.println(); // new line
    }
  }
  
  // method to read matrix elements as input
  public static int[][] readMatrix(int[][] temp) {
    for(int i=0; i<temp.length; i++) {
      for(int j=0; j<temp[0].length; j++) {
        // read matrix elements
        temp[i][j] = scan.nextInt();
      }
    }
    return temp;
  }

  // method to calculate the addition of two matrix
  public static int[][] addMatrix(int[][] a, int[][] b) {
    // calculate row and column size
    int row = a.length;
    int column = a[0].length;
    
    // declare a matrix to store resultant
    int sum[][] = new int[row][column];
    
    // calculate sum of two matrices
    // outer loop for row
    for(int i=0; i<row; i++) {
      // inner loop for column
      for(int j=0; j<column; j++) {
        // formula
        sum[i][j] = a[i][j] + b[i][j];
      }
    }
    
    // return resultant matrix
    return sum;
  }

}

Output:-

Enter row and column size:
3 3
Enter Matrix A:
1 2 3
4 5 6
7 8 9
Enter Matrix B:
5 6 7
8 9 10
3 1 2
Sum (C):
6 8 10
12 14 16
10 9 11

In this program, we had created Scanner class object as a private static variable which is outside of the main method because we need to read input values in two methods, in the main method to read row and column values and in readMatrix() method to read matrix elements. Therefore instead of creating Scanner class objects in both classes separately, it is better to create them as a static variable only once and use it multiple times anywhere in the program.

See more matrix programs in Java:- 

  1. Program to Print 3×3 Matrix 
  2. Sum of matrix elements in Java
  3. Sum of Diagonal Elements of Matrix in Java 
  4. Row sum and Column sum of Matrix in Java
  5. Subtraction of two matrices in Java 
  6. Transpose of a Matrix in Java 
  7. Matrix Multiplication in Java
  8. Menu-driven program for Matrix operations

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *