AP CSP Practice: FOR EACH Loops & List Traversal

Big Idea 3: Algorithms and Programming
Day 4 Practice • AP CSP Daily Question
🎯 Focus: Loops and Lists

Practice Question

Consider the following code segment:
myList ← [3, 7, 2, 9, 5]
sum ← 0

FOR EACH item IN myList
{
IF (item > 4)
{
sum ← sum + item
}
}
DISPLAY(sum)
What value is displayed as a result of executing this code segment?
What This Tests: Big Idea 3 covers list traversals and conditional logic. This question combines a FOR EACH loop with an IF statement to filter which items get processed.

Step-by-Step Trace

Iteration item item > 4? sum
Start 0
1 3 No 0
2 7 Yes 0 + 7 = 7
3 2 No 7
4 9 Yes 7 + 9 = 16
5 5 Yes 16 + 5 = 21

Only items greater than 4 are added: 7 + 9 + 5 = 21

Understanding FOR EACH

The FOR EACH loop visits every element in the list, one at a time:

FOR EACH item IN myList
   // item takes on each value: 3, then 7, then 2, then 9, then 5

The IF condition acts as a filter—only items that pass the condition (> 4) get added to sum.

Common Mistakes

Mistake: Answer C (26) - Adding all elements

If you got 26, you added ALL elements (3+7+2+9+5). The IF statement filters—only elements greater than 4 should be added.

Mistake: Forgetting 5 is greater than 4

5 > 4 is TRUE, so 5 gets added. Items equal to 4 would NOT be added (the condition is >, not >=).

💡 AP Exam Tip

When tracing loops with conditions, make a table with columns for: iteration number, current item, whether the condition is true, and running totals. This prevents skipping items or miscounting.

Difficulty: Medium • Time: 2-3 minutes • Topic: 3.6 Conditionals & 3.8 Iteration

Want More AP CSP Practice?

Get personalized help from an experienced AP CS teacher

AP CSP Study Guide Schedule 1-on-1 Tutoring
Back to blog