Curriculum

Curriculum

Swap Two Values Without Losing One

Scenario

Two students want to trade assigned study rooms: roomA = "101", roomB = "204".

  1. 1…
  2. 2…
  3. 3…

Try it yourself

Place the three assignment steps in order so neither room number is lost.

Reveal the explanation
  1. temp = roomA ("101")

    Saves roomA safely before roomA gets overwritten.

  2. roomA = roomB ("204")

    Moves roomB into roomA while "101" remains safe in temp.

  3. 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

Starting with a = 10 and b = 25, what are a and b after running "a = b; b = a"?
Show the answer and reasoning

Correct answer a = 25, b = 25 (the original 10 was lost)

The first assignment overwrites a with 25, so copying a back into b leaves both equal to 25.