10.1 2D Arrays


Nested Loops

So far we’ve only worked with while or for loops that are on their own. But you can actually put loops inside of loops, which is called nested loops.

2D Arrays

One common use for nested loops (for loops, in particular) is to traverse multi-dimensional arrays. So far, we’ve only learned one-dimensional arrays, where each element in the array is some data type. Multi-dimensional arrays have elements that are arrays themselves — it’s arrays within arrays.
This can be represented in a table where the indices of the outer list are rows and the indices of the inner lists are columns. For example, the following table could represent the following 2D list in Java:
String[][] list = { {"hello", "world", "code",}, {"docs", "slides", "sheets"}, {"google", "amazon", "facebook"}, {"this", "is", "java"} };
Note: You could technically write the sublists in one line, but it’s generally better style and easier to read if you write multi-dimensional lists like this.
Note: Notice that since it is a 2D array, there are 2 pairs of square brackets.

Next Section

10.2 Retrieving and Updating elements
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.