There is a special kind of loop that can be used with arrays that is called an enhanced for loop, or a for-each loop. This loop is much easier to write because it does not involve an index variable or the use of the [ ] square brackets. It just sets up a variable that is set to each value in the array successively. To set up a for-each loop, use for (type variable : arrayname) where the type is the type for elements in the array, and read it as “for each variable value in arrayname”.
int[] highScores = {10, 9, 8, 8};
String[] names = {"Jamal", "Emily", "Destiny", "Mateo"};
// for each loop: for each value in highScores
// for (type variable : arrayname)
for (int score : highScores)
{
// Notice no index or [ ] is needed, just the variable score
System.out.println( score );
}
// for each loop with a String array to print each name
// the type for variable name is String
for (String name : names)
{
System.out.println( name );
}
Use the enhanced for-each loop with arrays in the following cases: 1) you need to loop through all the elements of an array, 2) you don’t need to refer to each index, and don’t need to change the values of any of the elements.
The loop starts with the first element in the array (the one at index 0) and continues through in order to the last element in the array. This type of loop can only be used with arrays and some other collections of items like ArrayLists, which we will see in the next topic.
What if we had a loop that incremented the value of each element in the array. Would that work with an for-each loop? Unfortunately not! Because only the variable in the loop changes, not the real array values. We would need an indexed for loop to modify array elements.
Using a set of words, use any loop of your choosing to check if a word exists in an array. Return true if it does, otherwise false.