Write a program in java to add two matrices.

Example:

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.

  1. Input two matrices.
  2. Initialize the resultant matrix of same order with 0.
  3. 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.

Output

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.

Leave a Reply