Skip to content

Commit 7d32769

Browse files
committed
feat: Add two 3x3 matrices and print the result using enhanced for-loops
🧠 Logic: - Define two 3x3 matrices A and B. - Create matrix C to store the result of A + B. - Use nested `for` loops to perform element-wise addition. - Use enhanced `for-each` loops to print the resulting matrix C row by row. Signed-off-by: Somesh diwan <[email protected]>
1 parent 07c4fe1 commit 7d32769

File tree

1 file changed

+18
-21
lines changed

1 file changed

+18
-21
lines changed
Lines changed: 18 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,38 @@
11
public class AddingTwoMatrices {
22
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}};
55

66
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];
1410
}
1511
}
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*/
1913
{
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*/
2119
}
22-
System.out.println(""); /*Moves to the next line after printing a row*/
23-
}
2420
}
2521
}
2622

2723
/*
2824
Explanation:
29-
Outer Loop:
3025
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.
3228
Here, x represents a 1D array (a row in the matrix).
33-
Inner Loop:
3429
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[]).
3632
y represents the individual elements of the row.
33+
3734
Printing:
3835
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.
4138
*/

0 commit comments

Comments
 (0)