AP® Computer Science Principles · Big Idea 3 · Topic 3.1

Tracing Assignment Statements

An assignment statement takes whatever value is currently on the right side and stores it in the variable on the left. Order matters: each line uses the values that exist at that moment, not values set later.

Tracing means playing computer. You go line by line and keep a table with one column per variable, adding a row every time a value changes. When you hit an assignment statement like a <- 2, you don't check whether it's true the way you'd check an equation. You just compute the right side using whatever values are currently stored, then overwrite the left side variable with that result. The old value of a is gone the instant the new one is stored.

This is why order flips everything. If a is 1, then b is set to a, b copies the value 1 right then, as a snapshot. If a changes to 2 after that, b does not follow along. b only updates if another assignment statement explicitly sets it again. Swapping two variables shows why this matters: you cannot just say x <- y and y <- x, because the first line destroys x's original value before the second line can use it. That's why swaps need a temporary variable to hold one value safely while the other gets overwritten.

This topic is the foundation for everything else in the unit. Branches and loops are built entirely out of sequences of assignment statements, so tracing them carefully, one line and one updated value at a time, is the same skill you'll use to trace a loop that runs five times or a conditional that updates a counter. Get comfortable with the table-and-rows method here and loop tracing later will feel like the same move repeated.

Key terms

Assignment statement
An instruction that computes the value on the right side and stores it in the variable on the left.
Variable table
A trace tool listing each variable as a column, with a new row recorded every time a value changes.
Temporary variable
An extra variable used to hold a value safely while swapping or rearranging other variables' values.
Snapshot copy
The idea that assigning one variable to another copies its current value, not a live link that updates later.

Watch it explained

  1. How it worksWalk me through drawing a variable table that gains one updated row per line of code.
  2. Worked exampleFind what gets displayed after a is 1, b is a, a is 2, and the program displays b.
  3. Worked exampleTrace swapping x and y through a temporary variable when x starts at 7 and y starts at 3.
  4. Common mistakeWhy isn't the arrow in an assignment statement the same as the equals sign in mathematics?

Check yourself

Your turn1 of 2
a is set to 14. b is set to a. Then a is set to 33. What value does the program display when it displays b?

End of topic.