Add Two Matrices (of same size) | Java Programs

Output:

*** Addition Of Two Matrices ***

Input number of rows of matrix: 2
Input number of columns of matrix: 2

Input elements of first matrix: 
1   2
4   5
Input the elements of second matrix: 
3   1
4   7
Sum of the matrices:-
4   3 
8   12 

Click Here For Java Online Compiler

Solution:

import java.util.Scanner;

public class AddTwoMatrices {

    public static void main(String args[]) {
        int rows, columns, i, d;
        Scanner scanner = new Scanner(System.in);
        System.out.println("*** Addition Of Two Matrices ***" + "\n");
        System.out.print("Input number of rows of matrix: ");
        rows = scanner.nextInt();
        System.out.print("Input number of columns of matrix: ");
        columns = scanner.nextInt();
        System.out.println();
        int array1[][] = new int[rows][columns];
        int array2[][] = new int[rows][columns];
        int sum[][] = new int[rows][columns];

        System.out.println("Input elements of first matrix: ");

        for (i = 0; i < rows; i++) {
            for (d = 0; d < columns; d++) {
                array1[i][d] = scanner.nextInt();
            }
        }

        System.out.println("Input the elements of second matrix: ");

        for (i = 0; i < rows; i++) {
            for (d = 0; d < columns; d++) {
                array2[i][d] = scanner.nextInt();
            }
        }

        for (i = 0; i < rows; i++) {
            for (d = 0; d < columns; d++) {
                sum[i][d] = array1[i][d] + array2[i][d];
            }
        }

        System.out.println("Sum of the matrices:-");

        for (i = 0; i < rows; i++) {
            for (d = 0; d < columns; d++) {
                System.out.print(sum[i][d] + "   ");
            }

            System.out.println();
        }
    }
}
Share This :

Related Post



sentiment_satisfied Emoticon