Task 3 of 9 · 0 solved · 9 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

5.1 Arrays — length and traversal

Lesson

Visiting every element

arr.length tells you how many elements an array has. To visit them all, loop an index i from 0 up to but not including arr.length. The valid indices are 0 through length - 1; there is no element at index length.


Worked example

int[] nums = {10, 20, 30};
for (int i = 0; i < nums.length; i++) {
    System.out.println(nums[i]);
}

nums.length is 3, so i runs 0, 1, 2 and prints 10, 20, 30.


▶ Try it: run this to print every element. Change the array (add or remove values) and re-run — the loop still fits, because it uses nums.length.



What does nums.length give for {10, 20, 30}?


The valid indices of an array of length 3 are...


Type exactly what this prints:

int[] vals = {5, 10, 15};
for (int i = 0; i < vals.length; i++) {
    System.out.println(vals[i]);
}

Order the three parts of the traversal loop header: for ( _ ; _ ; _ ).


True or false?