Java Program to Add Two Matrices

Matrix addition is a basic arithmetic operation where two matrices of the same dimensions are added together to produce a new matrix. Each element of the resulting matrix is obtained by adding corresponding elements from the two matrices. This operation is vital in data science, physics, engineering, and more, where matrices are used to represent data or systems of equations.

Problem Statement

Our task is to create Java programs that can add two matrices. It is essential that the matrices have the same dimensions, as matrix addition is undefined for matrices of different sizes. We need to ensure our program can handle any matrices of the same size provided by the user or defined within the code.

Example:

Consider the addition of two 2×2 matrices:

Matrix A:

Matrix B:

The result of A + B is:

Java Programs for Adding Two Matrices

Program 1: Static Input for Matrix Addition

Let’s start with a Java program that uses predefined matrices to demonstrate how to add them:

public class MatrixAdditionStatic {
    public static void main(String[] args) {
        int[][] matrixA = {
            {1, 2},
            {3, 4}
        };
        int[][] matrixB = {
            {5, 6},
            {7, 8}
        };

        if (!areMatricesEqual(matrixA, matrixB)) {
            System.out.println("Matrices must have the same dimensions for addition.");
            return;
        }

        int[][] resultMatrix = addMatrices(matrixA, matrixB);
        System.out.println("Matrix After Addition: ");
        printMatrix(resultMatrix);
    }

    private static int[][] addMatrices(int[][] matrixA, int[][] matrixB) {
        int rows = matrixA.length;
        int cols = matrixA[0].length;
        int[][] result = new int[rows][cols];

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                result[i][j] = matrixA[i][j] + matrixB[i][j];
            }
        }
        return result;
    }

    private static boolean areMatricesEqual(int[][] matrixA, int[][] matrixB) {
        if (matrixA.length != matrixB.length || matrixA[0].length != matrixB[0].length) {
            return false;
        }
        return true;
    }

    private static void printMatrix(int[][] matrix) {
        for (int[] row : matrix) {
            for (int value : row) {
                System.out.print(value + " ");
            }
            System.out.println();
        }
    }
}

Output

Matrix After Addition: 
6 8
10 12

Explanation:

This program initializes two 2×2 matrices and uses the addMatrices function to compute their sum. It iterates through each element, adds corresponding elements, and stores the result in a new matrix. The printMatrix function displays the resulting matrix. Method areMatricesEqual, which checks if the two matrices have the same dimensions. If they don’t, it prints an error message and terminates the program. If they do have the same dimensions, the addition proceeds as before.

Program 2: Dynamic Input for Matrix Addition

Now, let’s write a program that allows the user to input their matrices:

import java.util.Scanner;

public class MatrixAdditionDynamic {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the number of rows and columns for Matrix A:");
        int rowsA = scanner.nextInt();
        int colsA = scanner.nextInt();

        System.out.println("Enter the number of rows and columns for Matrix B:");
        int rowsB = scanner.nextInt();
        int colsB = scanner.nextInt();

        if (rowsA != rowsB || colsA != colsB) {
            System.out.println("Matrices must have the same dimensions for addition.");
            scanner.close();
            return;
        }

        int[][] matrixA = new int[rowsA][colsA];
        int[][] matrixB = new int[rowsB][colsB];

        System.out.println("Enter the elements for Matrix A:");
        readMatrix(scanner, matrixA);

        System.out.println("Enter the elements for Matrix B:");
        readMatrix(scanner, matrixB);

        int[][] resultMatrix = addMatrices(matrixA, matrixB);
        System.out.println("Result of adding Matrix A and B:");
        printMatrix(resultMatrix);

        scanner.close();
    }

    private static void readMatrix(Scanner scanner, int[][] matrix) {
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                matrix[i][j] = scanner.nextInt();
            }
        }
    }

    private static int[][] addMatrices(int[][] matrixA, int[][] matrixB) {
        int rows = matrixA.length;
        int cols = matrixA[0].length;
        int[][] result = new int[rows][cols];

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                result[i][j] = matrixA[i][j] + matrixB[i][j];
            }
        }
        return result;
    }

    private static void printMatrix(int[][] matrix) {
        for (int[] row : matrix) {
            for (int value : row) {
                System.out.print(value + " ");
            }
            System.out.println();
        }
    }
}

Output

Enter the number of rows and columns for Matrix A:
3
3
Enter the number of rows and columns for Matrix B:
3
3
Enter the elements for Matrix A:
4
2
1
3
4
3
2
3
2
Enter the elements for Matrix B:
1
2
3
4
5
6
7
8
9
Result of adding Matrix A and B:
5 4 4
7 9 9
9 11 11

Explanation:

In this above program, the user specifies the dimensions of the matrices and inputs their elements. The program then adds the matrices using the same addMatrices function from the static version and displays the result.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.