Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
A student wants to swap a and b, and writes
After the program, both variables hold 3. Explain what went wrong, line by line, and write a correct swap in two different ways.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Plan. Follow the four lines and look for the moment when a value is lost.
a = 7 and b = 3. Now a is 7 and b is 3.a = b puts the value of b, which is 3, into a. The old value 7 is gone.b = a puts the value of a, which is now 3, into b. So b gets 3 again.Both hold 3. The 7 was lost in step 2, before we had saved it.
Two correct ways.
temp = a, then a = b, then b = temp.a, b = b, a.Check. After either way, a is 3 and b is 7.
Answer: The first value of a was overwritten before it was saved. Save it in temp first, or use a, b = b, a.
Log in to join the discussion.
Loading…