Swapping without a third variable — Aptitude Question
Swapping without a third variable: What does the pseudocode print? Answer and worked solution on CodeKairo.
- Topic: Pseudocode
- Section: Programming MCQs
- Difficulty: Easy
- Time target: 60 seconds
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, bOptions
- 5 12
- 12 5
- 17 12
- 12 17
Show the answer and the worked solution
Correct answer: A. 5 12
Worked solution
- Set a = a + b makes a = 12 + 5 = 17, while b is still 5.
- Set b = a - b makes b = 17 - 5 = 12, which is the original a.
- Set a = a - b makes a = 17 - 12 = 5, which is the original b.
- 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.