For Each Loops List Traversal
Share
Practice Question
scores <- [88, 72, 95, 67, 84, 91]
count <- 0
FOR EACH score IN scores
{
IF (score >= 80)
{
count <- count + 1
}
}
DISPLAY(count)The loop examines each score and increments count when score >= 80. Checking each element: 88 >= 80 (YES, count becomes 1), 72 >= 80 (NO), 95 >= 80 (YES, count becomes 2), 67 >= 80 (NO), 84 >= 80 (YES, count becomes 3), 91 >= 80 (YES, count becomes 4). Final count = 4. Four scores (88, 95, 84, 91) meet the condition. This demonstrates the counter pattern - using a variable to count items matching a condition.
A) 2 suggests only counting the first two qualifying scores (88 and 95) and stopping early, or perhaps only counting scores >= 90 instead of >= 80. Trace through ALL iterations - the loop doesn't stop after finding two matches.
B) 3 is close but misses one qualifying score. Common causes: (1) Forgetting to check all six scores, (2) Boundary error with >= vs > (thinking 80 doesn't count), or (3) Arithmetic error while tracking count increments.
D) 5 suggests counting either five of the six scores or making an off-by-one error. Check the condition carefully: 72 and 67 are both less than 80, so they do NOT increment count. Only four scores qualify.
Students often make boundary errors with >= vs >. The condition is score >= 80, meaning 80 WOULD qualify (though it's not in this list). Another error: not tracing through ALL iterations. FOR EACH always processes EVERY element - it doesn't stop early. Mark each score as it's checked to avoid losing count.
For counting loops: (1) Create a table showing the loop iteration, current element, whether condition is true, and count value after each iteration, (2) Update count ONLY when the condition is met, (3) Count from the table at the end. Write it out - mental counting leads to off-by-one errors!