Algorithm
-
Initialize Matrices:
- Declare and initialize two matrices, let's say
matrixA
andmatrixB
, with the desired dimensions.
- Declare and initialize two matrices, let's say
-
Check Compatibility:
- Ensure that the dimensions of both matrices are the same (number of rows and columns).
-
Create Result Matrix:
- Declare a new matrix,
resultMatrix
, with the same dimensions as the input matrices to store the result.
- Declare a new matrix,
-
Matrix Addition:
- Use nested loops to iterate through each element of the matrices.
- For each element at position (i, j), add the corresponding elements from
matrixA
andmatrixB
and store the result in the corresponding position inresultMatrix
.
-
Display Result:
- Optionally, display the contents of the
resultMatrix
to show the sum of the input matrices.
- Optionally, display the contents of the
Code Examples
#1 Code Example- Program to Add Two Matrices
Code -
Java Programming
public class AddMatrices {
public static void main(String[] args) {
int rows = 2, columns = 3;
int[][] firstMatrix = { {2, 3, 4}, {5, 2, 3} };
int[][] secondMatrix = { {-4, 5, 3}, {5, 6, 3} };
// Adding Two matrices
int[][] sum = new int[rows][columns];
for(int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
sum[i][j] = firstMatrix[i][j] + secondMatrix[i][j];
}
}
// Displaying the result
System.out.println("Sum of two matrices is: ");
for(int[] row : sum) {
for (int column : row) {
System.out.print(column + " ");
}
System.out.println();
}
}
}
Copy The Code &
Try With Live Editor
Output
Sum of two matrices is:
-2 8 7
10 8 6
-2 8 7
10 8 6
Demonstration
Java Programing Example to Add Two Matrix Using Multi-dimensional Arrays-DevsEnv