6.3. Searching for Matching Elements in an Array
You want to find the first element in an array that matches a specified value.
for statement to loop through an array,
and use a
break statement once a match has been
When you are searching for the first element in an array that matches
a specified value, you should use a
statement, as shown in Recipe 6.2,
but with the addition of a
break statement to
exit the loop once the match has been found.
break statement used within a
for statement causes the loop to exit once it is
encountered. Note that the
break statement is
generally placed within an
if statement, so it
is reached only when a certain condition is met. The importance of
break statement when searching for the first
matching element is two-fold. First of all, you should not needlessly
loop through the remaining elements of an array once the match has
been found, since it would waste processing time. In the following
break statement exits the loop
after the second iteration, saving six more needless iterations.
Imagine the savings if there were a thousand more elements.
break statement is vital when
searching for the first match because it ensures that only the first
element is matched and that subsequent matches are ignored. If the
break statement is omitted in the following
example, all matching elements are displayed, as opposed to the first
// Create an array with eight elements. myArray ...