For two integer variables, if arithmetic assignments are allowed and overflow…

2018

For two integer variables, if arithmetic assignments are allowed and overflow is ignored, what is the minimum number of temporary variables needed to swap their contents?

Answer: D. 0ConceptA temporary variable is auxiliary storage distinct from the two variables being updated. A swap can use a reversible transformation so that both…

  1. A.

    1

  2. B.

    2

  3. C.

    3

  4. D.

    0

Attempted by 208 students.

Show answer & explanation

Correct answer: D

Concept

A temporary variable is auxiliary storage distinct from the two variables being updated. A swap can use a reversible transformation so that both original values remain recoverable during intermediate assignments; this can reduce auxiliary space.

Application

Let a = 5 and b = 3. Use only a and b:

  1. Set a = a + b, so a = 8 and b = 3.

  2. Set b = a - b, so b = 5 while a = 8.

  3. Set a = a - b, so a = 3 and b = 5.

Cross-check

The final pair (a, b) = (3, 5) is the reverse of the initial pair (5, 3), and no third storage location was introduced. The no-overflow assumption keeps every arithmetic assignment valid.

Therefore, the minimum number of temporary variables is 0.

Explore the full course: Dsssb Tgt Computer Science Paper 2

Loading lesson…