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!


Leave a Comment

(required)

(required)

Formatting Your Comment

The following XHTML tags are available for use:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

URLs are automatically converted to hyperlinks.