AP CSP Day 38 Linear Search Traversal
Share
Big Idea 3
Day 38 Practice
Focus: Linear Search Traversal
Practice Question
Consider a procedure to find if a value exists in a list:
PROCEDURE contains(list, target)
{
FOR EACH item IN list
{
IF (item = target)
{
RETURN true
}
}
RETURN false
}Why This Answer?
The RETURN false after the loop only executes if the loop completes without finding target. This is correct linear search logic.
Why Not the Others?
A) Linear search works on unsorted lists.
B) Returns true when target IS found.
D) FOR EACH on empty list simply doesn't execute - no error.
Common Mistake
Watch Out!
Misunderstanding when RETURN false executes. It's OUTSIDE the loop, so only runs if target not found.
AP Exam Tip
Watch RETURN placement. Inside loop = early exit on success. After loop = runs if loop completes.