AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Easyswappingtracing

~60s

Swapping without a third variable

What does the pseudocode print?

Integer a, b
Set a = 12
Set b = 5
Set a = a + b
Set b = a - b
Set a = a - b
Print a, b
Show the answer and the worked solution

Correct answer: A.

5 12

Worked solution

  1. Set a = a + b makes a = 12 + 5 = 17, while b is still 5.
  2. Set b = a - b makes b = 17 - 5 = 12, which is the original a.
  3. Set a = a - b makes a = 17 - 12 = 5, which is the original b.
  4. The print statement therefore shows 5 12.

Answer: 5 12.

The idea

The additive swap idiom exchanges two values without a temporary. Recognising it saves the trace, but writing the pair of values beside every assignment is the habit that never fails.

Shortcut. The last two lines keep a + b = 17 fixed, so once b becomes 12 the other value must be 17 − 12 = 5: the output is the originals exchanged, 5 12.

Common trap. "17 12" is the state after the second assignment; a candidate who stops there never applies Set a = a − b, so a still holds the sum 17.

Swapping without a third variable — Aptitude Question

Swapping without a third variable: What does the pseudocode print? Answer and worked solution on CodeKairo.

Question

What does the pseudocode print?

Integer a, b
Set a = 12
Set b = 5
Set a = a + b
Set b = a - b
Set a = a - b
Print a, b

Options

  1. 5 12
  2. 12 5
  3. 17 12
  4. 12 17
Show the answer and the worked solution

Correct answer: A. 5 12

Worked solution

  1. Set a = a + b makes a = 12 + 5 = 17, while b is still 5.
  2. Set b = a - b makes b = 17 - 5 = 12, which is the original a.
  3. Set a = a - b makes a = 17 - 12 = 5, which is the original b.
  4. The print statement therefore shows 5 12.

Answer: 5 12.

The idea

The additive swap idiom exchanges two values without a temporary. Recognising it saves the trace, but writing the pair of values beside every assignment is the habit that never fails.

Shortcut. The last two lines keep a + b = 17 fixed, so once b becomes 12 the other value must be 17 − 12 = 5: the output is the originals exchanged, 5 12.

Common trap. "17 12" is the state after the second assignment; a candidate who stops there never applies Set a = a − b, so a still holds the sum 17.

All Pseudocode questions · placement mock tests