Skip to content

Commit eff0c28

Browse files
committed
feat: Demonstrate 2D array declaration, iteration, and various declaration syntaxes
🧠 Logic: - Initializes a 3×3 array `B` with literal values and prints its elements using nested loops indexing rows and columns (`B.length` and `B[0].length`). - Shows multiple ways to declare and initialize 2D arrays (`int[][] A`, `int[][] c`, `int[][] D`, `int[] E[]`, and combined declarations). - Highlights declaration pitfalls with mixed dimensions in a single statement (e.g., `int[] M, F[]` vs. `int[] I, J, K, L`). - Includes comments explaining how `B[0].length` provides the column count for iteration. Signed-off-by: Somesh diwan <[email protected]>
1 parent 8a66912 commit eff0c28

File tree

1 file changed

+17
-9
lines changed

1 file changed

+17
-9
lines changed
Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,20 @@
11
public class TwoDArray {
22
public static void main(String[] args) {
3-
43
int B[][] = {{1, 2, 3}, {2, 4, 6}, {1, 3, 5}};
5-
for (int i = 0; i < B.length; i++)
6-
{
4+
5+
for (int i = 0; i < B.length; i++) {
76
for (int j = 0; j < B[0].length; j++)
7+
/*
8+
Gives the number of columns (using the first row's length)
9+
refers to the first row of the 2D array, which is `{1, 2, 3}`.
10+
It's a 1D array itself. `B[0]`
11+
So:
12+
- = `{1, 2, 3}` `B[0]`
13+
- = `3` (the number of columns in the first row) `B[0].length`
14+
15+
That's why in the loop condition is used to determine how many times to iterate through each column
16+
- it gives us the width of the array (number of columns). `B[0].length`
17+
*/
818
{
919
System.out.print(B[i][j] + " ");
1020
}
@@ -14,16 +24,14 @@ public static void main(String[] args) {
1424
int A[][] = new int[5][5];
1525

1626
int c[][];
17-
1827
c=new int[5][5];
1928

20-
int[][] D = new int[5][5];
21-
29+
int[][]D = new int[5][5];
2230
int[]E[] = new int[5][5];
2331

2432
int[]M,F[];
2533
M=new int[5]; //1D Array.
26-
F=new int[5][5]; //Its Two D Array.
34+
F=new int[5][5]; //It's Two D Array.
2735

2836
int[]G, H[]; //2D Array
2937

@@ -37,6 +45,6 @@ public static void main(String[] args) {
3745
Key Points:
3846
int[] represents a 1D array.
3947
int[][] represents a 2D array.
40-
Avoid mixing , and ; in a single declaration.*/
48+
Avoid mixing, and; in a single declaration.*/
4149
}
42-
}
50+
}

0 commit comments

Comments
 (0)