InternDoor

Python · 1 min

How to swap numbers without a third variable

Learn how arithmetic operations swap values without a third variable, and why fixed-size integer languages risk overflow during intermediate sums.

Practise PythonMore videos

The quiz

What does this print?

  1. 5 9
  2. 14 5
  3. 9 5
  4. 9 14
Show the answer

C. 9 5

Transcript

Can you swap two numbers without creating an extra temporary variable?

First, you combine both numbers into one variable. Then, subtract to isolate the first value, and subtract again to get the second.

Adding five and nine makes fourteen. Subtracting nine puts five into b. Finally, subtracting five puts nine into a, which prints nine and five.

Here is the key idea: this swaps without a third variable, but in fixed-size languages the sum can overflow, so XOR swaps are taught.

Always track the intermediate sum carefully. Never risk an arithmetic overflow in fixed integer types, and remember no third variable was ever needed.

Look at the screen right now and trace the steps. What does this snippet print? Pause the video and choose between A, B, C, or D.

The correct answer is C, not B. The values swapped completely, so variable a now holds nine while variable b safely holds five.

Save this walkthrough to revise it later. You can practice more arithmetic puzzles and core placement concepts directly on InternDoor today.

More study videos

All videos
Learned it? See who is hiring

Engineering internships and entry-level jobs in India, newest first.