views:

115

answers:

4

Possible Duplicate:
Swapping two variable value without using 3rd variable

we have int a=4; int b=7;

can i swap these no.s without using third variable

+1  A: 
a=a+b;
b=a-b;
a=a-b;
fredley
Sure it is -- see gspr's answer.
Hogan
@Hogan realised that very quickly and changed answer, sorry for confusion.
fredley
doesn't work for all values
Jeff Meatball Yang
@yang , how can you say?
Guri
@Guri Jeff is correct, this is susceptible to overflow. The XOR method would be better.
fredley
@fredley: Only in programming languages with broken arithmetic. There *are* actually programming languages which *can* add two numbers correctly.
Jörg W Mittag
@Jörg :-O wow...
fredley
@fredley: I find it kind of sad that the fact that 2 billion plus 2 billion equals 4 billion is *still* considered an exciting and exotic feature in 2010.
Jörg W Mittag
+2  A: 

The precise implementation of course depends on the programming language you're using, but check out XOR swap.

An example in C could be

#include <stdio.h>

/* Swaps the content pointed to by a and b. The memory pointed to is
   assumed non-overlapping! */

void swap(int* a, int* b)
{
  *a = (*a)^(*b);
  *b = (*a)^(*b);
  *a = (*a)^(*b);
}

int main(int argc, char** argv)
{
  int a = 4;
  int b = 7;
  printf("a=%d, b=%d\n", a, b);
  swap(&a, &b);
  printf("a=%d, b=%d\n", a, b);
  return 0;
}

Important: As Prasoon Saurav commented on the question itself, this answer to another question is more correct than mine, seeing as it is important that the two variables reside at non-overlapping locations in memory. My example does not check for this.

gspr
A: 

Sure: a,b = b,a works in various programming languages.

In others you can use the xor trick.

sepp2k
+1  A: 

a=a+b; //a=11,b=7

b=a-b; //a=11,b4

a=a-b; //a=7,b=4

or

a=a*b;

b=a/b;

a=b/a;

but careful with this method, overflow or underflow is possible for some combinations.

ratty
All liable to overflow/underflow with certain number combinations.
dty