AP CSP Day 60: Side Effects & Mutation | Cycle 2
Share
Functional programming style minimizes side effects by designing procedures that always return a value and never modify external state, making programs easier to reason about and test. When a procedure both returns a value and modifies a global list, the caller must account for two separate changes, increasing the chance of errors. AP CSP Cycle 2 side-effect review questions present complex programs with multiple procedures that interact through shared mutable state, and ask students to trace the final state of all modified variables after a sequence of calls. This is the highest-complexity tracing challenge in the AP CSP QOTD series and tests mastery of all the concepts covered across both cycles.
📚 Study the Concept First (Optional) Click to expand ▼
Side Effects Mastery: Tracing Complex Shared State
Functional vs. Imperative Style
A functional approach designs procedures to take all inputs as parameters and return results without modifying external state. This makes programs easier to reason about because a procedure's behavior depends only on its inputs. An imperative approach freely uses and modifies global state, which is powerful but harder to trace.
Multi-Procedure Interaction
When multiple procedures share a mutable list, every call that modifies the list changes the context for all subsequent calls. The final state of the shared list depends on the exact sequence in which procedures are called.
Practice Question
What is displayed after the following code runs?
nums ← [5, 10, 15, 20, 25]
i ← LENGTH(nums)
REPEAT UNTIL i < 1
{
IF nums[i] MOD 10 = 0
{
REMOVE(nums, i)
}
i ← i - 1
}
DISPLAY(nums)
DISPLAY(LENGTH(nums))The loop traverses backward from i=5 to 1. i=5: nums[5]=25, 25 MOD 10=5 (not 0, skip). i=4: nums[4]=20, 20 MOD 10=0 (remove). nums=[5,10,15,25]. i=3: nums[3]=15, 15 MOD 10=5 (skip). i=2: nums[2]=10, 10 MOD 10=0 (remove). nums=[5,15,25]. i=1: nums[1]=5, 5 MOD 10=5 (skip). i=0: stop. Result: [5,15,25], length 3.
B) 10 is divisible by 10 and is removed. C) 20 is divisible by 10 and is removed. D) 25 is not divisible by 10 (25 MOD 10 = 5), so it remains.
Students confuse divisibility by 10 with having 0 as a digit. 25 MOD 10 = 5 (not divisible by 10). Also, backward traversal is specifically used here to avoid index-shifting problems when removing elements.
Backward traversal is the standard technique for removing elements during iteration. When you remove an element, earlier indices are unaffected, so decrementing i still visits every element correctly.
Keep Practicing!
Consistent daily practice is the key to AP CSP success.
AP CSP Resources Get 1-on-1 Help