AP CSA Unit 1 Day 6: Multi Step Reassignment
Share
Multi-Step Trace with Reassignment
Section 1.3 — Expressions and Assignment
Key Concept
Multi-step trace problems require tracking variable values through sequential reassignments. When a variable is reassigned, its previous value is permanently lost. A common AP exam pattern involves swapping values without a temporary variable, or using a variable's old value in an expression that also updates it. The key technique is to write down each variable's value after every statement, never relying on mental arithmetic. Pay special attention to statements like a = a + b; b = a - b; where the updated value of a is used in the next line.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (B) 3 5
This is the classic swap-without-temp pattern:
Start: a = 5, b = 3
a = a + b: a = 5 + 3 = 8. Now a = 8, b = 3.
b = a - b: b = 8 - 3 = 5. Now a = 8, b = 5.
a = a - b: a = 8 - 5 = 3. Now a = 3, b = 5.
The values of a and b have been swapped.
Why Not the Others?
(A) This would be the output if the swap did nothing. But the three lines effectively exchange the values of a and b.
(C) This uses the intermediate value of a (8) but forgets that the third line updates a again.
(D) This reverses the order of the output variables. The code prints a first, then b.
Common Mistake
The key is tracing each line using the CURRENT values, not the original ones. After line 3, a is 8 (not 5), so line 4 uses a = 8. Many students accidentally use the original value of a.
AP Exam Tip
For swap and reassignment questions, keep a running table of variable values. Update it after every line. Never look back at the original values once a variable has been reassigned.