|
| 1 | +import java.util.*; |
| 2 | + |
| 3 | +class AddingMatrix { |
| 4 | + public static void main(String[] args) { |
| 5 | + Scanner sc = new Scanner(System.in); |
| 6 | + |
| 7 | + System.out.println("Enter the number of rows for the first matrix:"); |
| 8 | + int aRows = sc.nextInt(); |
| 9 | + System.out.println("Enter the number of columns for the first matrix:"); |
| 10 | + int aCols = sc.nextInt(); |
| 11 | + int a[][] = new int[aRows][aCols]; |
| 12 | + |
| 13 | + System.out.println("Enter the elements for the first matrix:"); |
| 14 | + for (int i = 0; i < aRows; i++) { |
| 15 | + for (int j = 0; j < aCols; j++) { |
| 16 | + a[i][j] = sc.nextInt(); |
| 17 | + } |
| 18 | + } |
| 19 | + |
| 20 | + System.out.println("Enter the number of rows for the second matrix:"); |
| 21 | + int bRows = sc.nextInt(); |
| 22 | + System.out.println("Enter the number of columns for the second matrix:"); |
| 23 | + int bCols = sc.nextInt(); |
| 24 | + int b[][] = new int[bRows][bCols]; |
| 25 | + |
| 26 | + System.out.println("Enter the elements for the second matrix:"); |
| 27 | + for (int i = 0; i < bRows; i++) { |
| 28 | + for (int j = 0; j < bCols; j++) { |
| 29 | + b[i][j] = sc.nextInt(); |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + if (aRows != bRows || aCols != bCols) { |
| 34 | + System.out.println("Matrices cannot be added. They have different dimensions."); |
| 35 | + } else { |
| 36 | + int result[][] = new int[aRows][aCols]; |
| 37 | + for (int i = 0; i < aRows; i++) { |
| 38 | + for (int j = 0; j < aCols; j++) { |
| 39 | + result[i][j] = a[i][j] + b[i][j]; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + System.out.println("After adding the matrices:"); |
| 44 | + for (int i = 0; i < aRows; i++) { |
| 45 | + for (int j = 0; j < aCols; j++) { |
| 46 | + System.out.print(result[i][j] + " "); |
| 47 | + } |
| 48 | + System.out.println(); |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | +} |
0 commit comments