Skip to content

Commit c598c6c

Browse files
committed
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]>
1 parent d39b04e commit c598c6c

File tree

1 file changed

+11
-15
lines changed

1 file changed

+11
-15
lines changed

Section8LoopAB/src/ForEachLoop.java

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,15 @@
11
public class ForEachLoop {
2-
public static void main(String[] args)
3-
{
2+
public static void main(String[] args) {
43
int[][] matrix =
54
{
6-
{1, 2, 3},
7-
{4, 5, 6},
8-
{7, 8, 9}
5+
{1, 2, 3},
6+
{4, 5, 6},
7+
{7, 8, 9}
98
};
10-
119
// Outer for-each loop iterates through rows (1D arrays)
12-
for (int[] row : matrix)
13-
{
10+
for (int[] row : matrix) {
1411
// Inner for-each loop iterates through elements in the current row
15-
for (int element : row)
16-
{
12+
for (int element : row) {
1713
System.out.print(element + " ");
1814
}
1915
System.out.println(); // Move to the next line after each row
@@ -30,21 +26,21 @@ public static void main(String[] args)
3026
3127
Immutable Collections: When you don't intend to modify the collection/array.
3228
33-
3429
Key Points to Remember:
3530
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.
3731
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.
3934
35+
Works with Arrays and Collections:
4036
For-each loops are compatible with arrays and classes that implement the Iterable interface (e.g., ArrayList, HashSet).
4137
4238
No Manual Indexing:
4339
If you need indices, you'll need to use a traditional for loop instead.
4440
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.
4742
43+
However, if you need indexing or want to modify elements, you should use a traditional for loop.
4844
4945
Example with a 2D Array:
5046
To use a for-each loop with a 2D array, you need to understand that:

0 commit comments

Comments
 (0)