How to write Java program to add two matrices

Java Programming Java8Object Oriented Programming

To add two matrices −

  • Create an empty matrix
  • At each position in the new matrix, assign the sum of the values in the same position from the given two matrices i.e. if A[i][j] and B[i][j] are the two given matrices then, the value of c[i][j] should be A[i][j] + B[i][j]


Live Demo

public class AddingTwoMatrices{
   public static void main(String args[]){
      int a[][]={{1,2,3},{4,5,6},{7,8,9}};
      int b[][]={{1,1,1},{1,1,1},{1,1,1}};
      int c[][]=new int[3][3];

      for(int i = 0;i<3;i++){
         for(int j = 0;j<3;j++){
            c[i][j] = a[i][j]+b[i][j];
            System.out.print(c[i][j]+" ");


2 3 4
5 6 7
8 9 10
Published on 25-Apr-2018 08:34:21