3

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?

Community
  • 1
  • 1
Guri
  • 261
  • 2
  • 3
  • 10

4 Answers4

3
a=a+b;
b=a-b;
a=a-b;
Hogan
  • 69,564
  • 10
  • 76
  • 117
fredley
  • 32,953
  • 42
  • 145
  • 236
2

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.

Community
  • 1
  • 1
gspr
  • 11,144
  • 3
  • 41
  • 74
1

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
  • 13,216
  • 29
  • 75
  • 108
0

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

In others you can use the xor trick.

sepp2k
  • 363,768
  • 54
  • 674
  • 675