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
  1. Ax = 3, y = 3
  2. Bx = 7, y = 3
  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.
Practice this topic Back to topic

Related calculators

Books on Programming Basics (Pseudocode Tracing) Ad

As an Amazon Associate I earn from qualifying purchases.

More Programming Basics (Pseudocode Tracing) questions

  1. The following program passes values along three variables. What are the values of a, b and c after it runs?
  2. The following program repeatedly multiplies x by 3. What is the value of n after it runs?
  3. The following for loop increases i by 2. What is the value of s after it runs?
  4. In the following nested loop, the inner loop starts from the outer variable i. What is the value of c after it runs?
  5. The following program has a condition inside a nested loop. What is the value of c after it runs?