ITPEC IP April 2026 Question 6

The data is exchanged between variable A and variable B. When variable TMP is used to temporarily store data, which of the following is the procedure for exchanging data correctly? Here, “x ← y” represents that the data of “x” is replaced with the data of “y”.

Explanation

TMP ← A, A ← B, B ← TMP — save A before overwriting it, then give B the saved value.

Trace it with A = 1 and B = 2:

  • •TMP ← A: TMP = 1, the original A is safe
  • •A ← B: A = 2, the old A is overwritten but survives in TMP
  • •B ← TMP: B = 1

A and B are exchanged. The variable that is overwritten first (A) must be the one copied into TMP, and TMP must be the source of the last assignment.

Answer (b)

Why not others:

  • •(a) — saves A in TMP but never uses it: after A ← B, the step B ← A copies the new A, so both end as 2
  • •(c) — saves B, the value that is not about to be lost; A ← B destroys the original A, and B ← TMP just gives B back its own value, so both end as 2
  • •(d) — saves B and never uses TMP; A ← B then B ← A leaves both as 2

Key rule: A swap through a temporary variable is TMP ← X, X ← Y, Y ← TMP: save the variable you overwrite first, and finish by reading from TMP.

Algorithm and Programming · AI-written, may contain errors

This question comes from an official ITPEC past paper. ITPEC Practice is an independent study tool and is not affiliated with ITPEC. See the official IP past-paper collection or Report an issue.