AP CSP Day 31: Variables & Assignment | Cycle 2

Key Concepts

Advanced variable tracing requires identifying errors in assignment sequences where a programmer uses a variable before it has been assigned, or accidentally overwrites a value needed later. Swap algorithms without a temporary variable are a classic source of bugs: writing x ← y followed by y ← x loses the original value of x before it can be saved. AP CSP Cycle 2 questions challenge students to spot these assignment errors in pseudocode and determine the incorrect output that results. Predicting the intended versus actual output is a key error-analysis skill.

📚 Study the Concept First (Optional) Click to expand ▼

Variable Errors: Spotting What's Wrong

Use-Before-Assignment Bug

A use-before-assignment error occurs when code reads a variable before any value has been stored in it. The result is undefined behavior. In AP CSP pseudocode, this appears when a variable is referenced on the right side of an assignment before it ever appears on the left side.

Overwrite Bug

An overwrite error occurs when a value needed later is replaced before it is used. The classic swap error - a ← b followed by b ← a - overwrites a's original value before saving it, so b ends up with b's value rather than a's.

Common Trap: Assuming code that looks logical is correct. Always trace the specific values rather than the intent. The bug is in what the code does, not what the programmer meant.
Exam Tip: On error-spotting questions, build a trace table and follow the code exactly as written. Do not interpret what the code was supposed to do - trace what it actually does.
Big Idea 3: Algorithms & Programming
Cycle 2 • Day 31 Practice • Hard Difficulty
Focus: Variables & Assignment

Practice Question

What is displayed after the following code runs?

p ← 2
q ← 5
p ← p + q
q ← p - q
p ← p - q
DISPLAY(p)
DISPLAY(q)
Why This Answer?

This is the classic swap-without-a-temporary-variable algorithm. Trace: p=2, q=5. After p ← p+q: p=7. After q ← p-q: q=7-5=2. After p ← p-q: p=7-2=5. Final values: p=5, q=2. The values are swapped.

Why Not the Others?

A) The values are exchanged, not preserved. C) p is modified again in the third step — students who stop tracing after line 4 get stuck on p=7. D) q is updated in the second step to 2, not kept at 5.

Common Mistake
Watch Out!

Students stop tracing too early, reporting p=7 after the third line and forgetting that p is reassigned again. Every assignment must be traced to completion.

AP Exam Tip

When a variable is reassigned multiple times in sequence, always use the most recently updated value. Never skip a step or use a stale value.

Keep Practicing!

Consistent daily practice is the key to AP CSP success.

AP CSP Resources Get 1-on-1 Help
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.