|
1 | 1 | public class AddingTwoMatrices { |
2 | 2 | public static void main(String[] args) { |
3 | | - int A[][] = {{3,5,9},{7,6,2},{4,3,5}}; |
4 | | - int B[][] = {{1,5,2},{6,8,4},{3,9,7}}; |
| 3 | + int A[][] = {{3, 5, 9}, {7, 6, 2}, {4, 3, 5}}; |
| 4 | + int B[][] = {{1, 5, 2}, {6, 8, 4}, {3, 9, 7}}; |
5 | 5 |
|
6 | 6 | int C[][] = new int[3][3]; |
7 | | - |
8 | | - for (int i=0;i<A.length;i++) |
9 | | - { |
10 | | - for (int j=0; j<A[0].length;j++) |
11 | | - { |
12 | | - C[i][j]=A[i][j]+B[i][j]; |
13 | | - |
| 7 | + for (int i = 0; i < A.length; i++) { |
| 8 | + for (int j = 0; j < A[0].length; j++) { |
| 9 | + C[i][j] = A[i][j] + B[i][j]; |
14 | 10 | } |
15 | 11 | } |
16 | | - for(int x[]:C) /*Iterates over each row (1D array) of the 2D array C*/ |
17 | | - { |
18 | | - for(int y:x) /*Iterates over each element in the current row*/ |
| 12 | + for (int x[] : C) /*Iterates over each row (1D array) of the 2D array C*/ |
19 | 13 | { |
20 | | - System.out.print(y+" "); /*Prints the element*/ |
| 14 | + for (int y : x) /*Iterates over each element in the current row*/ |
| 15 | + { |
| 16 | + System.out.print(y + " "); /*Prints the element*/ |
| 17 | + } |
| 18 | + System.out.println(""); /*Moves to the next line after printing a row*/ |
21 | 19 | } |
22 | | - System.out.println(""); /*Moves to the next line after printing a row*/ |
23 | | - } |
24 | 20 | } |
25 | 21 | } |
26 | 22 |
|
27 | 23 | /* |
28 | 24 | Explanation: |
29 | | -Outer Loop: |
30 | 25 |
|
31 | | - for (int x[] : C) loops through each row (x[]) in the 2D array C. |
| 26 | +Outer Loop: |
| 27 | +for (int x[] : C) loops through each row (x[]) in the 2D array C. |
32 | 28 | Here, x represents a 1D array (a row in the matrix). |
33 | | -Inner Loop: |
34 | 29 |
|
35 | | - for (int y : x) loops through each element (y) in the current row (x[]). |
| 30 | +Inner Loop: |
| 31 | +for (int y : x) loops through each element (y) in the current row (x[]). |
36 | 32 | y represents the individual elements of the row. |
| 33 | +
|
37 | 34 | Printing: |
38 | 35 |
|
39 | | - System.out.print(y + " ") prints each element (y) in the current row on the same line. |
40 | | - System.out.println(""); moves to a new line after finishing one row, ensuring the next row starts on a new line. |
| 36 | +System.out.print(y + " ") prints each element (y) in the current row on the same line. |
| 37 | +System.out.println(""); moves to a new line after finishing one row, ensuring the next row starts on a new line. |
41 | 38 | */ |
0 commit comments