Algorithm


  1. Initialize Matrices:

    • Declare and initialize two matrices, let's say matrixA and matrixB, with the desired dimensions.
  2. Check Compatibility:

    • Ensure that the dimensions of both matrices are the same (number of rows and columns).
  3. Create Result Matrix:

    • Declare a new matrix, resultMatrix, with the same dimensions as the input matrices to store the result.
  4. 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 and matrixB and store the result in the corresponding position in resultMatrix.
  5. Display Result:

    • Optionally, display the contents of the resultMatrix to show the sum of the input matrices.

 

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

x
+
cmd
Sum of two matrices is:
-2 8 7
10 8 6
Advertisements

Demonstration


Java Programing Example to Add Two Matrix Using Multi-dimensional Arrays-DevsEnv