|
| 1 | +# Matrix Sum |
| 2 | + |
| 3 | +WAP to add 2 matrices |
| 4 | + |
| 5 | +## Solution |
| 6 | + |
| 7 | +### [Java Implementation](./MatrixSum.java) |
| 8 | + |
| 9 | +```java |
| 10 | +/** |
| 11 | + * Print Matrix Sum |
| 12 | + */ |
| 13 | + |
| 14 | +import java.util.*; |
| 15 | + |
| 16 | +class MatrixSum { |
| 17 | + public static void main(String[] args) { |
| 18 | + Scanner input = new Scanner (System.in); |
| 19 | + System.out.print("Enter the number of rows: "); |
| 20 | + int row = input.nextInt(); |
| 21 | + System.out.print("Enter the number of columns: "); |
| 22 | + int col = input.nextInt(); |
| 23 | + |
| 24 | + // Input the 1st Matrix |
| 25 | + int[][] arr1 = new int[row][col]; |
| 26 | + System.out.println("Enter the elements of first matrix: "); |
| 27 | + for (int i=0; i<row; i++) { |
| 28 | + for (int j=0; j<col; j++) { |
| 29 | + System.out.print("arr1[" + i + "][" + j + "] = "); |
| 30 | + arr1[i][j] = input.nextInt(); |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + // Input the 2nd Matrix |
| 35 | + int[][] arr2 = new int[row][col]; |
| 36 | + System.out.println("Enter the elements of second matrix: "); |
| 37 | + for (int i=0; i<row; i++) { |
| 38 | + for (int j=0; j<col; j++) { |
| 39 | + System.out.print("arr2[" + i + "][" + j + "] = "); |
| 40 | + arr2[i][j] = input.nextInt(); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + // Print 1st matrix |
| 45 | + System.out.println("First Matrix: "); |
| 46 | + for (int i=0; i<row; i++) { |
| 47 | + for (int j=0; j<col; j++) { |
| 48 | + System.out.print(arr1[i][j] + " "); |
| 49 | + } |
| 50 | + System.out.println(""); |
| 51 | + } |
| 52 | + |
| 53 | + // Print 2nd matrix |
| 54 | + System.out.println("Second Matrix: "); |
| 55 | + for (int i=0; i<row; i++) { |
| 56 | + for (int j=0; j<col; j++) { |
| 57 | + System.out.print(arr2[i][j] + " "); |
| 58 | + } |
| 59 | + System.out.println(""); |
| 60 | + } |
| 61 | + |
| 62 | + // Print Transpose matrix |
| 63 | + int[][] sum = new int[row][col]; |
| 64 | + System.out.println("Sum of input matrices: "); |
| 65 | + for (int i=0; i<row; i++) { |
| 66 | + for (int j=0; j<col; j++) { |
| 67 | + sum[i][j] = arr1[i][j] + arr2[i][j]; |
| 68 | + System.out.print(sum[i][j] + " "); |
| 69 | + } |
| 70 | + System.out.println(""); |
| 71 | + } |
| 72 | + } |
| 73 | +} |
| 74 | +``` |
0 commit comments