4 Replies - 1246 Views - Last Post: 27 January 2011 - 02:50 PM Rate Topic: -----

#1 Sahib28  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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 ..?
please help
Is This A Good Question/Topic? 0
  • +

Replies To: Swapping values without using third variable?

#2 bhandari  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 9
  • View blog
  • 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?
Was This Post Helpful? 1
  • +
  • -

#3 Sahib28  Icon User is offline

  • New D.I.C Head

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

Re: Swapping values without using third variable?

Posted 27 January 2011 - 11:29 AM

View Postbhandari, 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.
Was This Post Helpful? 0
  • +
  • -

#4 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2871
  • View blog
  • Posts: 11,026
  • 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
Was This Post Helpful? 1
  • +
  • -

#5 mostyfriedman  Icon User is offline

  • The Algorithmi
  • member icon

Reputation: 727
  • View blog
  • 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.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1