Programming Basics (Pseudocode Tracing)
The two assignments in the following program were meant to swap the values of x and y. What are the values of x and y after it runs?
integer: x ← 3, y ← 7
x ← y
y ← x
- Ax = 3, y = 3
- Bx = 7, y = 3
- Cx = 7, y = 7
Show answer and explanation
Answer: C. x = 7, y = 7
In the pseudocode, assignments are executed one at a time from top to bottom. x ← y makes x 7, and the original value 3 is lost at that point. The following y ← x then copies the new value of x, 7, into y, so x = 7 and y = 7. To swap values, first save the original value in a temporary variable, as in t ← x, x ← y, y ← t.
- A. This is the result if y ← x ran first. In this program x ← y comes first.
- B. This assumes the swap worked. The original value 3 of x is lost at x ← y.
- C. Correct. x ← y makes x 7, and y ← x then assigns 7 as well.
Continue: 9 more Programming Basics (Pseudocode Tracing) questions