</>

Technology

Java Programs

Difficulty

Beginner

Interview Question

Write a Java program to add two matrices.

Answer

Add Two Matrices in Java

Java
public class AddTwoMatrix {
    public static void main(String args[]) {
        int m, n, c, d;

        int first[][]  = { { 1, 2 }, { 5, 10 }, { 2, 6 } };
        int second[][] = { { 2, 6 }, { 1, 2 },  { 5, 3 } };

        m = first.length;       // number of rows
        n = first[0].length;    // number of columns

        int sum[][] = new int[m][n];

        System.out.println("Calculating Sum of 2 matrices....");

        for (c = 0; c < m; c++)
            for (d = 0; d < n; d++)
                sum[c][d] = first[c][d] + second[c][d];
                // replace '+' with '-' to subtract matrices

        System.out.println("Sum of 2 matrices....");

        for (c = 0; c < m; c++) {
            for (d = 0; d < n; d++)
                System.out.print(sum[c][d] + "\t");
            System.out.println();
        }
    }
}

Output

CODE
Calculating Sum of 2 matrices....
Sum of 2 matrices....
3    8
6    12
7    9

Key Concepts

  • first.length → number of rows
  • first[0].length → number of columns
  • Replace + with - to subtract matrices
  • Both matrices must have the same dimensions

Automation Testing Relevance

Used when comparing test result matrices — e.g., comparing expected vs actual data grids from a web table.

Follow AutomateQA