Swap without Temporary Variable

When we’re programming, if we want to swap values of two integer values, the “normal” way we do it would look like:

x = 5
y = 3

temp = x
x = y
y = temp

We need a temporary variable as a container to hold a value first then do the swap.

What if in some situation you can’t use the extra variable? How would you do it?

Well, let’s forget computer programming but pick up some little math we learned in elementary school:

x = 5
y = 3

x = x - y (=2)
y = x + y (=5)
x = y - x (=3)

Here we go!

This entry was posted in Programming and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>