add two matrices of the same size in java

Solutions on MaxInterview for add two matrices of the same size in java by the best coders in the world

showing results for - "add two matrices of the same size in java"
Juana
06 Jan 2019
1public class AddTwoMatrices {
2
3    public static void main(String[] args) {
4
5        int r, c, i, j;
6        Scanner in = new Scanner(System.in);
7
8        System.out.println("Enter the row size of the matrix:");
9        r = in.nextInt();
10
11        System.out.println("Enter the column size of the matrix:");
12        c = in.nextInt();
13
14        int array1[][] = new int[r][c];
15        int array2[][] = new int[r][c];
16        int sum[][] = new int[r][c];
17
18        System.out.println("Input elements of the first matrix:");
19        for (i = 0; i < r; i++) {
20            for (j = 0; j < c; j++) {
21                array1[i][j] = in.nextInt();
22            }
23        }
24
25        System.out.println("Input elements of the second matrix:");
26        for (i = 0; i < r; i++) {
27            for (j = 0; j < c; j++) {
28                array2[i][j] = in.nextInt();
29            }
30        }
31
32        for (i = 0; i < array1.length; i++) {
33            for (j = 0; j < array2.length; j++) {
34                sum[i][j] = array1[i][j] + array2[i][j];
35                System.out.print(sum[i][j] + "\t");
36            }
37            System.out.println();
38        }
39    }
40}