Matrix addition in Java is performed by adding the corresponding elements of two matrices. Both matrices must have the same number of rows and columns.
Illustration:
Input:
A[][] = {{1, 2}, {3, 4}},B[][] = {{1, 1}, {1, 1}}
Output:{{2, 3}, {4, 5}}Input:
A[][] = {{2, 4}, {3, 4}},B[][] = {{1, 2}, {1, 3}}
Output:{{3, 6}, {4, 7}}
Approach to Add Two Matrices
- Take two matrices of the same dimensions.
- Create a new matrix to store the result.
- Traverse both matrices using nested loops.
- Add the corresponding elements of both matrices.
- Store the sum in the corresponding position of the result matrix.
- Print the resultant matrix.
public class Geeks {
public static void main(String[] args)
{
// Input matrices
int A[][] = { { 1, 2 }, { 3, 4 } };
int B[][] = { { 1, 1 }, { 1, 1 } };
// Dimensions of the matrix
int rows = A.length;
int cols = A[0].length;
// Resultant matrix to store the sum
int sum[][] = new int[rows][cols];
// Adding two matrices
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sum[i][j] = A[i][j] + B[i][j];
}
}
// Printing the resultant matrix
System.out.println("Resultant Matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// Print elements on the same line
System.out.print(sum[i][j] + " ");
}
// Move to the next line after printing each row
System.out.println();
}
}
}
Output
Resultant Matrix: 2 3 4 5
Explanation
- Take two matrices of the same size.
- Add corresponding elements of both matrices.
- Store the result in a new matrix.
- Print the resultant matrix.