Swap Two Values Without Losing One
Scenario
Two students want to trade assigned study rooms: roomA = "101", roomB = "204".
- 1…
- 2…
- 3…
Try it yourself
Place the three assignment steps in order so neither room number is lost.
Reveal the explanation
- temp = roomA ("101")
Saves roomA safely before roomA gets overwritten.
- roomA = roomB ("204")
Moves roomB into roomA while "101" remains safe in temp.
- roomB = temp ("101")
Completes the swap: roomA is now "204" and roomB is "101".
If you write roomA = roomB; roomB = roomA without saving roomA first, both variables become "204" and "101" disappears forever.
Review first
Your turn
Trace swapping seatLeft = "A1" and seatRight = "B2" step by step, writing all three variable values after each step.
Common mistake Writing seatLeft = seatRight first without saving seatLeft in temp.
Check your work
After step 1: temp="A1"; step 2: seatLeft="B2"; step 3: seatRight="A1".
Quick check
This browser could not save your progress. Changes last until you leave the page.