Learn how to find what you're looking for in an array!
Arrays are utilized for many operations in various programs, such as storing large groups of data in an ordered manner.
Suppose we ran a debate team, and wanted to keep track of all the students who came to practice one day. We could create an array that stored a list of students in the order they showed up:
To access an individual element, or name from this array, we can do so by using the []
notation:
Since this list of orders is fairly small, it’s easy to access the individual names, but oftentimes, arrays can have hundreds, thousands, or even millions of values. How is it possible to access all values when it’s not clear where a specific value might be stored? There needs to be a systematic way to access all of these values! Luckily, iteration, or traversing, an array can provide a simple solution.
Iterating over an array requires the use of a for or while loop:
This for loop iterates through every value in the debaters
list, and prints out the value at every index.
You may notice the use of the keyword length
. This returns the current size of an array. An array with six values is considered an array of length
6. The length of an array corresponds to the number of elements in an array, not the last index value in an array. If you recall, arrays start at index 0 - an array with six elements will start at 0 and end at index 5.
Therefore, the last index in an array will always be array.length - 1
. The for loop is set to i < debaters.length
, so that the greatest value of i
will always be one less than the length of the array.
Notice that the for loop starts at the first element (zero) and ends at the last element (array.length - 1). Each time through the loop, the value of i
accesses the element at index i
. This simple for loop is able to loop through the array, regardless of how many items there are in the array.
This traversal can also be written using a while loop:
Notice that the variable index
is outside of the while loop. This ensures that the variable index
isn’t reset to 0 every time the while loop starts a new iteration. The value of index
is increased by one at the end of the while loop, ensuring that the next index in the array will be accessed.
The debate team also has a list that tracks how many students were late or on time to practice in a given day.
Using iteration, print the number of students who were late to practice.
Hint:
The .equals
method can be used to check if a String
is equal to another String
.