class Matrix { int m,n; int first[][] = new int [10][10]; int second[][] = new int [10][10]; int sum[][] = new int[10][10]; void getValue() { System.out.println("\nEnter the number of rows and columns of each matrix:"); m = Integer.parseInt(System.console().readLine()); n = Integer.parseInt(System.console().readLine()); } void getFirst() { System.out.println("\nEnter elements for first matrix:"); for(int i=0;i<m;i++) for(int j=0;j<n;j++) first[i][j] = Integer.parseInt(System.console().readLine()); } void getSecond() { System.out.println("\nEnter elements for second matrix:"); for(int i=0;i<m;i++) for(int j=0;j<n;j++) second[i][j] = Integer.parseInt(System.console().readLine()); } void matrixSum() { for(int i=0;i<m;i++) for(int j=0;j<n;j++) sum[i][j] = first[i][j] + second[i][j]; System.out.println(“Addition of two matrices is:”); System.out.println(); for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { System.out.print(sum[i][j]); System.out.print("\t"); } System.out.println(); } } } class Matrixmain { public static void main(String A[]) { Matrix m = new Matrix(); m.getValue(); m.getFirst(); m.getSecond(); m.matrixSum(); } }
Output: |
---|
Enter the number of rows and columns of each matrix: |
2 |
2 |
Enter elements for first matrix: |
1 |
2 |
3 |
4 |
Enter elements for second matrix: |
4 |
3 |
2 |
1 |
Addition of two matrices is: |
5 |
5 |
5 |
5 |