Problem: Write a Java program to add two matrices.
Example:
m1 = {{1,2}, {2,1}}; m2 = {{1,1}, {1,1}}; m1+m2 = {{2,3}, {3,2}};
In Java, we can represent a matrix by an 2-dimensional array.
For example, m1 ={{1,2},{2,1}}
is a 2D array of order 2×2, where m1[i][j]
is the matrix element of the ith row and jth column.
It is important to know that we can only add matrices if they are of the same order.
Assuming the order of the matrices are same, we can add them in Java as follows:
- Input two matrices.
- Initialize the resultant matrix of the same order with 0.
- Loop through the matrix elements and apply
res[i][j] = m1[i][j]+m2[i][j]
. - Output the resultant matrix.
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:
2 2 2
7 2 0
5 3 3
In the above program, we are adding and displaying the result in the same nested loop.
By doing so, we did not have to write an additional nested for loop for displaying the resultant matrix.