Java program to Add Two Matrices Using Two Dimensional Array

The program adds two matrices with the help of two-dimensional arrays. It is achieved by frequently adding an element of first array with an element at the same index of second array and the sum stores to new array. Given two matrices below :

Java program to add two matrices

Java program to Add Two Matrices Using Two Dimensional Array

It uses the Scanner Class to accept input from the user in both the matrices and then using a nested loop, addition is performed on those matrices are performed.

Program:

public class AddTwoMatrices {
    public static void main(String[] args) {
        Scanner ed = new Scanner(System.in);
        int row, col, i, j;
        System.out.println("Enter number of rows");
        row = ed.nextInt();
        System.out.println("Enter number of column");
        col = ed.nextInt();
        int[][] a = new int[row][col];
        int[][] b = new int[row][col];
        int[][] sum = new int[row][col];
        System.out.println("Enter first matrix");
        for (i = 0; i < row; i++) {
            for (j = 0; j < col; j++) {
                a[i][j] = ed.nextInt();
            }
        }
        System.out.println("Enter Second matrix");
        for (i = 0; i < row; i++) {
            for (j = 0; j < col; j++) {
                b[i][j] = ed.nextInt();
            }
        }
        for (i = 0; i < row; i++) {
            for (j = 0; j < col; j++) {
                sum[i][j] = b[i][j] + a[i][j];
            }
        }
        System.out.println("Sum of two matrices");
        for (i = 0; i < row; i++) {
            for (j = 0; j < col; j++) {
                System.out.print(sum[i][j]+" ");
            }
            System.out.print("\n");
        }
    }
}

Output:

Enter number of rows
2
Enter number of column
3
Enter first matrix
8
5
3
2
1
4
Enter Second matrix
5
3
2
1
5
6
7
Sum of two matrices
13 8 5 
3 6 10 

 

Explanation :

  1. It accepts the size of the matrix ( row and column ) and also the values of the matrix as input from the user for the
  2. By traversing, every element of first array added to the corresponding element of another array
  3. Lastly, Printing the array on the output screen.

Leave a Reply