AP CSP Day 23: Variables & Assignment
Share
Variable tracing requires reading pseudocode line by line and updating each variable's value as assignment statements execute. A variable holds exactly one value at any moment; each new assignment replaces the previous value entirely. AP CSP exam review questions on variable assignment often involve multi-step sequences where the same variable is assigned multiple times, and students must report its value at a specific point in execution. Swap patterns, where two variables exchange values using a temporary variable, are a classic tracing challenge.
📚 Study the Concept First (Optional) Click to expand ▼
Variable Tracing: Review and Harder Cases
The Swap Problem
Swapping two variable values correctly requires a temporary variable. Without it, one value is lost. The correct pattern: temp ← a, then a ← b, then b ← temp. Skipping the temporary variable overwrites the original value of a before it is saved.
Sequential Dependency
In a sequence of assignments, each line uses the current values of variables at that moment. The expression on the right side is evaluated using current values before the result is stored into the left side variable.
Practice Question
What is displayed after the following code runs?
a ← 3
b ← 7
a ← a + b
b ← a - b
DISPLAY(a)
DISPLAY(b)Starting: a=3, b=7. After a ← a + b: a = 3+7 = 10. After b ← a - b: b = 10-7 = 3 (using the current value of a, which is now 10). Display shows 10 then 3.
A) Students who pick this use the current a (10) correctly for the first display but forget to update b. B is correct because b changes too. C) Both variables are modified by the code. B) This reverses the displayed order or uses wrong intermediate values.
Students use the original value of a (3) instead of the updated value (10) when computing b ← a - b. Always use the most recent value of a variable.
When a variable appears on both sides of an assignment, the right side is evaluated first using current values, then the result is stored on the left. Update your trace immediately.
Keep Practicing!
Consistent daily practice is the key to AP CSP success.
AP CSP Resources Get 1-on-1 Help