Sum of two Matrix In JAVA

We are going to calculate the sum of two matrix and containing its rows and columns.

To make this program, we need to declare two dimensional array of type integer. Firstly it calculates the length of the both the arrays. Now we need to make a matrix out of it. To make the matrix we will use the for loop. By making use of the for loop the rows and column will get divide. This process will be performed again for creating the second matrix.

After getting both the matrix with us, we need to sum both the matrix. The both matrix will be added by using the for loop with matrix1[i][j]+matrix2[i][j]. The output will be displayed by using the println() method.

Here is the code of this program:

class MatrixSum{
public static void main(String[] args)  {
int matrix1[][]= {{7,8,9},{1,5,2}};
int matrix2[][]= {{1,6,4},{2,7,3}};
System.out.println("Number of Row= " + matrix1.length);
System.out.println("Number of Column= " + matrix1[1].length);
int l = matrix1.length;
System.out.println("Matrix 1 : ");
for(int i = 0; i < l; i++) {
for(int j = 0; j <= l; j++) {
System.out.print(" "+ matrix1[i][j]);
}
System.out.println();
}
int m = matrix2.length;
System.out.println("Matrix 2 : ");
for(int i = 0; i < m; i++) {
for(int j = 0; j <= m; j++) {
System.out.print(" "+matrix2[i][j]);
}
System.out.println();
}
System.out.println("Addition of both matrix : ");
for(int i = 0; i < m; i++) {
for(int j = 0; j <= m; j++) {
System.out.print(" "+(matrix1[i][j]+matrix2[i][j]));
}
System.out.println();
}
}
}

Enjoy Code.