Matrix Addition in Java

In this article, we are going to discuss how to add two matrix using java. For adding two matrix first we take input for both matrices matrix1 matrix2.

Matrix addition example:-

In matrix addition we have to add corresponding cells of both the matrices. An example of 3 matrix addition is given below:-

matrix addition in java

Java Code for matrix addition

Steps for matrix additon in java

Here we are going to write code for square matrix addition –

  • Ask size of input matrix from user
  • Declare three int 2D array of desired size, two array for storing input matrix and one is for storing result matrix ( new matrix after addition)
  • take input for both the inuput matrix from user using scanner. If you don’t know how take 2D array input from user using scanner you can learn from here https://gangforcode.com/multidimensional-array-in-java/
  • now run for loops to acess each cells of both the matrices. add corresponding cells and store in the result matrix or 2D array.
  • print the result matrix

Matrix addition Java Code


package gangforcode;
import java.util.*;
public class matrixAddition {
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the size of matrix");
    int n=sc.nextInt();
    int[][] matrix1= new int[n][n];
    int[][] matrix2= new int[n][n];
    System.out.println("Enter the first matrix");
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++) {
            matrix1 [i][j]=sc.nextInt();
    }
}
System.out.println("Enter the second matrix");
        for(int i=0;i<n;i++)
{
    for(int j=0;j<n;j++) {
        matrix2 [i][j]=sc.nextInt();
}}
     int sum[][]= new int[n][n];
  for(int i=0;i<n;i++) {
      for(int j=0;j<n;j++) {
         sum[i][j]= matrix1[i][j]+matrix2[i][j]; 

      }
  }
  System.out.println(Result after matrix addition");
  for(int i=0;i<n;i++) {
      for(int j=0;j<n;j++) {
          System.out.print(sum[i][j]+ "  " );
      }

  System.out.println();
  }
}}

In the above code we first take both matrices input from user after that we added both matric and printed the resultant matrix.

Java Matrix Addition Output

matrix addition program

Similar Java tutorials

Hello World – https://gangforcode.com/java-code-to-print-hello-world/
data types in java – https://gangforcode.com/data-types-in-java/
identifiers in java – https://gangforcode.com/identifiers-in-java/
keywords in java – https://gangforcode.com/keywords-in-java/
Multidimensional Array in Java – https://gangforcode.com/multidimensional-array-in-java/

5 thoughts on “Matrix Addition in Java”

Leave a Comment