You are here

Java program to add two matrices

Java program to add two matrices of any order. The code adds two matrices, you can modify it to add any number of matrices. You can create a Matrix class and create it's objects and then create an add method which sum the objects, then you can add any number of matrices by repeatedly calling the method using a loop.

Java programming source code

  1. import java.util.Scanner;
  2.  
  3. class AddTwoMatrix
  4. {
  5.    public static void main(String args[])
  6.    {
  7.       int m, n, c, d;
  8.       Scanner in = new Scanner(System.in);
  9.      
  10.       System.out.println("Enter the number of rows and columns of matrix");
  11.       m = in.nextInt();
  12.       n  = in.nextInt();
  13.      
  14.       int first[][] = new int[m][n];
  15.       int second[][] = new int[m][n];
  16.       int sum[][] = new int[m][n];
  17.      
  18.       System.out.println("Enter the elements of first matrix");
  19.      
  20.       for (c = 0; c < m; c++)
  21.          for (d = 0; d < n; d++)
  22.             first[c][d] = in.nextInt();
  23.            
  24.       System.out.println("Enter the elements of second matrix");
  25.      
  26.       for (c = 0 ; c < m ; c++)
  27.          for (d = 0 ; d < n ; d++)
  28.             second[c][d] = in.nextInt();
  29.            
  30.       for (c = 0; c < m; c++)
  31.          for (d = 0; d < n; d++)
  32.              sum[c][d] = first[c][d] + second[c][d];  //replace '+' with '-' to subtract matrices
  33.  
  34.       System.out.println("Sum of the matrices:");
  35.      
  36.       for (c = 0; c < m; c++)
  37.       {
  38.          for (d = 0; d < n; d++)
  39.             System.out.print(sum[c][d]+"\t");
  40.          
  41.          System.out.println();
  42.       }
  43.    }
  44. }

Download Add matrix program class file.

Output of program:
add matrix