Rotating three variables — Pseudocode Aptitude Question
Rotating three variables: What is printed? Answer and worked solution on CodeKairo.
- Topic: Pseudocode
- Section: Programming MCQs
- Difficulty: Medium
- Time target: 75 seconds
Question
What is printed?
Integer p, q, r, t
Set p = 2
Set q = 5
Set r = 9
Set t = p
Set p = r
Set r = q
Set q = t
Print p, q, rOptions
- 2 5 9
- 5 9 2
- 9 2 5
- 9 5 2
Show the answer and the worked solution
Correct answer: C. 9 2 5
Worked solution
- Set t = p stores 2, leaving p = 2, q = 5, r = 9.
- Set p = r makes p = 9.
- Set r = q makes r = 5.
- Set q = t makes q = 2, so the print statement shows 9 2 5.
Answer: 9 2 5.
The idea
A three-way rotation needs one temporary to hold the value that is overwritten first. Tracking every variable after every line is what stops the values getting shuffled by one place.
Shortcut. Eliminate: Set p = r makes p 9, ruling out "2 5 9" and "5 9 2", and Set q = t makes q the old p, 2, ruling out "9 5 2".
Common trap. "9 5 2" reads the code as a plain swap of p and r, overlooking that r is then overwritten with 5 and q receives the saved 2.