Menu
Coddy logo textTech

Matrix Addition & Substraction

Part of the Logic & Flow section of Coddy's Java journey — lesson 5 of 59.

To add or subtract two matrices, they must have the same dimensions (i.e., the same number of rows and columns). The operation is performed element-wise, meaning you add or subtract corresponding elements in each matrix.

For example:

Matrix A:
1 2
3 4

Matrix B:
5 6
7 8

A + B:
(1+5) (2+6)
(3+7) (4+8)

Result:
6  8
10 12

Matrix multiplication is more complex and it will be covered in a later section.

challenge icon

Challenge

Easy

Create a method named subMatrices that takes two 2D arrays (matrices) as input and return their difference as a new 2D array.

Cheat sheet

To add or subtract matrices, they must have the same dimensions. The operation is performed element-wise on corresponding elements.

Example of matrix addition:

Matrix A:
1 2
3 4

Matrix B:
5 6
7 8

A + B:
(1+5) (2+6)
(3+7) (4+8)

Result:
6  8
10 12

For incompatible dimensions, return new int[0][0] (an empty array).

Try it yourself

// Write your code only inside the class. Do not write main() or any code outside this class.
class SubMatrices {
    public static int[][] subMatrices(int[][] matrix1, int[][] matrix2) {
        // Write your code here
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow