Code for swapping values without using third variable ..?
please help
Swapping values without using third variable?
Page 1 of 14 Replies - 1033 Views - Last Post: 27 January 2011 - 02:50 PM
Replies To: Swapping values without using third variable?
#2
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?
a=10;
b=5;
a = a + b; ==> a=15
b = a - b; ==> b=10
a = a - b; ==> a=5
Simple isn't it?
#3
Re: Swapping values without using third variable?
Posted 27 January 2011 - 11:29 AM
#4
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
a = a^b (^ is XOR)
b = a^b
a = a^b
#5
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.
Page 1 of 1
|
|

New Topic/Question
Reply




MultiQuote








|