Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 28, 2021 08:45 pm GMT

Accessing Elements in 2D Arrays in Java

The two-dimensional (2D) array is a useful data structure. Like one-dimensional arrays, 2D arrays work well with for loops.

Here is a 2D array in Java:

int[][] arr = {  {0, 1, 2, 3, 4},  {5, 6, 7, 8, 9},  {10, 11, 12, 13, 14}};

The int[][] declaration means that arr is a 2D array of int values. Since there are two pairs of [], the array has two dimensions.

Look at this 2D array. It is actually an array of arrays. The array arr has a length of 3. It has three elements, or rows. Each row is an array of length 5:

{0, 1, 2, 3, 4}{5, 6, 7, 8, 9}{10, 11, 12, 13, 14}

The first array is arr[0]. The second and third arrays are arr[1] and arr[2] respectively. A for loop can access each of these arrays using an index:

for (int i=0; i < arr.length; i++) {  int[] row = arr[i];  System.out.println( Arrays.toString(row) );}

Here is the output:

[0, 1, 2, 3, 4][5, 6, 7, 8, 9][10, 11, 12, 13, 14]

The for loop accesses each row. Since the row is also an array, an inner for loop can access each of its elements:

for (int i=0; i < arr.length; i++) {  int[] row = arr[i];  for (int j=0; j < row.length; j++) {    System.out.println(i + "," + j + ": " + arr[i][j]);  }}

Here is the output:

0,0: 00,1: 10,2: 20,3: 30,4: 41,0: 51,1: 61,2: 71,3: 81,4: 92,0: 102,1: 112,2: 122,3: 132,4: 14

In the output, the first number is the row index. The second number is the column index. The third number is the element at that position of the 2D array.

Note how two indexes are required when accessing a single element of the 2D array. For example, arr[1][3] contains the int value 8. The for loop accesses each row in order. Once it has a row, then it uses an inner for loop to access its int values in order.

Here is a complete example:

public class Example {  public static void main(String[] args) {    int[][] arr = {      {0, 1, 2, 3, 4},      {5, 6, 7, 8, 9},      {10, 11, 12, 13, 14}    };    for (int i=0; i < arr.length; i++) {      int[] row = arr[i];      for (int j=0; j < row.length; j++) {        System.out.println(i + "," + j + ": " + arr[i][j]);      }    }  }}

When using 2D arrays, use two indexes. The first index is for the row. The second index is for the column. In other words, each element of a 2D array is an array. The first index accesses an array element. Then use a second index to access the elements in that array. To facilitate this, use a for loop with an inner for loop to provide the row and column indexes.

Thanks for reading.

Follow me on Twitter @realEdwinTorres for more programming tips.


Original Link: https://dev.to/realedwintorres/accessing-elements-in-2d-arrays-in-java-1o7i

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To