AP CSP Day 37: Number Systems
Share
Practice Question
What is displayed after the following code runs?
nums ← [4, 7, 2, 9, 1, 6]
result ← 0
FOR EACH n IN nums
{
IF n MOD 2 = 1
{
result ← result + n
}
}
DISPLAY(result)The code accumulates only odd numbers (n MOD 2 = 1). Checking each: 4 is even (skip), 7 is odd (add), 2 is even (skip), 9 is odd (add), 1 is odd (add), 6 is even (skip). Sum of odds: 7 + 9 + 1 = 17.
A) 29 is the sum of all elements (4+7+2+9+1+6), not just the odd ones. B) 12 is the sum of even elements (4+2+6). D) 22 does not match any valid subset sum.
Students either sum all elements without applying the MOD filter, or confuse MOD 2 = 1 (odd) with MOD 2 = 0 (even), computing the sum of even numbers instead.
When you see an accumulator inside a loop with a condition, identify two things separately: what gets added (the accumulator update) and when it gets added (the filter condition).
Keep Practicing!
Consistent daily practice is the key to AP CSP success.
AP CSP Resources Get 1-on-1 Help