You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
feat: Display 2D array elements using nested for-each loops
🧠 Logic:
- Define a 2D array (`matrix`) with 3 rows and 3 columns.
- Use an outer for-each loop to iterate over each row (1D array).
- Use an inner for-each loop to iterate over each element of the row.
- Print elements in a structured matrix format, row by row.
Signed-off-by: Somesh diwan <[email protected]>
Copy file name to clipboardExpand all lines: Section8LoopAB/src/ForEachLoop.java
+11-15Lines changed: 11 additions & 15 deletions
Original file line number
Diff line number
Diff line change
@@ -1,19 +1,15 @@
1
1
publicclassForEachLoop {
2
-
publicstaticvoidmain(String[] args)
3
-
{
2
+
publicstaticvoidmain(String[] args) {
4
3
int[][] matrix =
5
4
{
6
-
{1, 2, 3},
7
-
{4, 5, 6},
8
-
{7, 8, 9}
5
+
{1, 2, 3},
6
+
{4, 5, 6},
7
+
{7, 8, 9}
9
8
};
10
-
11
9
// Outer for-each loop iterates through rows (1D arrays)
12
-
for (int[] row : matrix)
13
-
{
10
+
for (int[] row : matrix) {
14
11
// Inner for-each loop iterates through elements in the current row
15
-
for (intelement : row)
16
-
{
12
+
for (intelement : row) {
17
13
System.out.print(element + " ");
18
14
}
19
15
System.out.println(); // Move to the next line after each row
@@ -30,21 +26,21 @@ public static void main(String[] args)
30
26
31
27
Immutable Collections: When you don't intend to modify the collection/array.
32
28
33
-
34
29
Key Points to Remember:
35
30
Read-Only Access:
36
-
You can use the for-each loop to read the elements but cannot modify the array or collection elements directly. Modifications should be done with a standard for loop using indices.
37
31
38
-
Works with Arrays and Collections:
32
+
You can use the for-each loop to read the elements but cannot modify the array or collection elements directly.
33
+
Modifications should be done with a standard for loop using indices.
39
34
35
+
Works with Arrays and Collections:
40
36
For-each loops are compatible with arrays and classes that implement the Iterable interface (e.g., ArrayList, HashSet).
41
37
42
38
No Manual Indexing:
43
39
If you need indices, you'll need to use a traditional for loop instead.
44
40
45
-
The for-each loop is ideal for reading elements of arrays or collections. However, if you need indexing or want to modify elements, you should use a traditional for loop.
46
-
It's a matter of choosing the right tool for the task. 😊
41
+
The for-each loop is ideal for reading elements of arrays or collections.
47
42
43
+
However, if you need indexing or want to modify elements, you should use a traditional for loop.
48
44
49
45
Example with a 2D Array:
50
46
To use a for-each loop with a 2D array, you need to understand that:
0 commit comments