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

~75s

Rotating three variables

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, r
Show the answer and the worked solution

Correct answer: C.

9 2 5

Worked solution

  1. Set t = p stores 2, leaving p = 2, q = 5, r = 9.
  2. Set p = r makes p = 9.
  3. Set r = q makes r = 5.
  4. 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.

Rotating three variables — Pseudocode Aptitude Question

Rotating three variables: What is printed? Answer and worked solution on CodeKairo.

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, r

Options

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

Correct answer: C. 9 2 5

Worked solution

  1. Set t = p stores 2, leaving p = 2, q = 5, r = 9.
  2. Set p = r makes p = 9.
  3. Set r = q makes r = 5.
  4. 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.

All Pseudocode questions · placement mock tests