Searching for Elements
In this lesson, you will learn to search for array elements using:
forforeachwhiledo...while
Searching using for
The
for loop provides access to the index, which is convenient for searching. Line 1, Char 1
Searching using foreach
foreach is simpler, but does not provide an index. Line 1, Char 1
Searching using while
Suitable when the search logic is dynamic.
Line 1, Char 1
Searching using do...while
The loop executes at least once.
Line 1, Char 1
Summary
for— best option if you need to know the index.foreach— when you just need to check for the presence of an element.while— convenient for complex search conditions.do...while— rarely used, but guarantees one iteration.
Exercises
- Implement search using
for.
Line 1, Char 1
- Implement search using
foreach.
Line 1, Char 1
- Implement search using
while.
Line 1, Char 1
- Implement search using
do…while.
Line 1, Char 1