**Retrieving and Updating Elements**

**Retrieving and Updating Elements**

You retrieve and update elements in a multi-dimensional list the same way you would for 1D lists, except now you have to deal with multiple levels of indices. The table below shows how you would retrieve each value in `list`

. Do you see any patterns?

0 | 1 | 2 | |
---|---|---|---|

0 | list[0][0] | list[0][1] | list[0][2] |

1 | list[1][0] | list[1][1] | list[1][2] |

2 | list[2][0] | list[2][1] | list[2][2] |

3 | list[3][0] | list[3][1] | list[3][2] |

You can also think about multi-dimensional lists this way:

The first index is the first “level” of the list. The second index is the second “level” of the list. It’s list-ception!

Let’s say we’re trying to retrieve `list[1][2]`

. How would we get there?

First, look at the first level. We need to retrieve the element at index 1. That would be:

Now we’re going to go a level deeper. The next index is 2, so that would be:

Therefore, `list[1][2]`

is `“sheets”`

!

To traverse a multidimensional array, you can use a nested for loop for however many “levels” you have. For a 2D array, you’ll need 2 for loops:

```
for (int row = 0; row < list.length; row++) {
for (int col = 0; col < list[row].length; col++) {
System.out.println(list[row][col]);
}
}
```

If we step through this code, we can see that the outer loop iterates through each of the inner arrays. The inner loop iterates through each element in the current inner array. The code will print out each element in `list`

in order.

__Practice__

## Asterisks

Fill a 3 X 3 string array so that the values in each row are "*", "**", "***". Print the values in 3 rows of 3 elements, each separated by a tab. Fill the array with values using a loop. Keep track of the total number of asterisks in the array, and print it below the array values.

__Previous Section__

__Next Section__

**Copyright © 2021 Code 4 Tomorrow. All rights reserved.**
The code in this course is licensed under the MIT License.
*If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact **classes@code4tomorrow.org** for inquiries.*