# Swapping values without using third variable?

Page 1 of 1

## 4 Replies - 1411 Views - Last Post: 27 January 2011 - 02:50 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=212410&amp;s=4474bbdb23a7c6cffa08fea50ad3651e&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 Sahib28

Reputation: 0
• Posts: 2
• Joined: 07-January 11

# Swapping values without using third variable?

Posted 27 January 2011 - 11:18 AM

Code for swapping values without using third variable ..?
Is This A Good Question/Topic? 0

## Replies To: Swapping values without using third variable?

### #2 bhandari

Reputation: 9
• Posts: 754
• Joined: 31-January 08

## Re: Swapping values without using third variable?

Posted 27 January 2011 - 11:27 AM

here is the logic:

a=10;
b=5;
a = a + b; ==> a=15
b = a - b; ==> b=10
a = a - b; ==> a=5

Simple isn't it?

### #3 Sahib28

Reputation: 0
• Posts: 2
• Joined: 07-January 11

## Re: Swapping values without using third variable?

Posted 27 January 2011 - 11:29 AM

bhandari, on 27 January 2011 - 11:27 AM, said:

here is the logic:

a=10;
b=5;
a = a + b; ==> a=15
b = a - b; ==> b=10
a = a - b; ==> a=5

Simple isn't it?

ya indeed it was .
thanks for the help.

### #4 Dogstopper

Reputation: 2950
• Posts: 11,217
• Joined: 15-July 08

## Re: Swapping values without using third variable?

Posted 27 January 2011 - 02:34 PM

There is another way to do this using bits and XOR operator. It's also the same operation all three times, so it's simpler to remember:

a = a^b (^ is XOR)
b = a^b
a = a^b

### #5 mostyfriedman

• The Algorithmi

Reputation: 729
• Posts: 4,473
• Joined: 24-October 08

## Re: Swapping values without using third variable?

Posted 27 January 2011 - 02:50 PM

I prefer the XOR method since with addition there is a chance for overflows.