6.3. Searching for Matching Elements in an Array
Problem
You want to find the first element in an array that matches a specified value.
Solution
Use a for statement to loop through an array,
and use a break statement once a match has been
found.
Discussion
When you are searching for the first element in an array that matches
a specified value, you should use a for
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.
A 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
the 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
example, the break statement exits the loop
after the second iteration, saving six more needless iterations.
Imagine the savings if there were a thousand more elements.
Furthermore, the 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
one only.
// Create an array with eight elements. myArray ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access