Write a program in java to **add two matrices.**

**Example:**

1 2 3 4 5 6 7 8 | m1 = {{1,2}, {2,1}}; m2 = {{1,1}, {1,1}}; m1+m2 = {{2,3}, {3,2}}; |

In Java, a matrix can be represented using a 2D array, for example `m1 ={{1,2},{2,1}}`

is a 2D array of order **2X2**, in which `m1[i][j]`

is the matrix element at ith row and jth column.

Also, the number of rows of the matrix is `m1.length`

and the number of columns is `m1[0].length`

.

Now, **the matrix addition is only possible if both the matrices have the same order**. So first we need to check the order, if both matrices have the same order then we can proceed to add them.

To add two matrices we simply need to follow the following steps.

- Input two matrices.
- Initialize the resultant matrix of same order with 0.
- Loop through the matrix element and apply
`res[i][j] = m1[i][j]+m2[i][j]`

.

Let’s see the source code to add two matrices in Java.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | public class Main { public static void main(String[] args) { //Matrix I int m1[][] = {{1,2,1}, {5,1,0}, {2,2,2}}; //Matrix II int m2[][] = {{1,0,1}, {2,1,0}, {3,1,1}}; //Check order of both the matrices if(m1.length != m2.length || m1[0].length != m2[0].length){ System.out.println("Matrices orders are not same, so Addition not possible "); return; } //Else both matrices has same order, so matrix addition is possible int res[][] = new int[m1.length][m1[0].length]; for(int i=0; i<m1.length; i++){ for(int j=0; j<m1[0].length; j++){ res[i][j] = m1[i][j]+m2[i][j]; //display the result System.out.print(res[i][j]+" "); } System.out.println(); } } } |

**Output**

1 2 3 | 2 2 2 7 2 0 5 3 3 |

In the above program, we are doing both addition and the display of the result in the same nested “for loop”. By doing so, we did not have to write the additional nested for loop for displaying the resultant matrix.

If you didn’t understand anything or have any suggestion then please comment below.