Suppose you have two variables, a and b. How can you swap their values without using a temporary variable and also without using the bitwise operator XOR?

See solution.

In a similar manner to the XOR solution, we can use simple addition and subtraction:

```
a = a + b;
b = a - b;
a = a - b;
```

## Comments

Sign uporlog in with Facebookto comment.Mehul ThakkarNow, can you think about swapping 3 variables(for ex. input,a=5,b=10,c=15 then output, a=15,b=5 and c=10) applying same rules as in this question

JayUsing the method above, swap a and c first and then swap b and c

sandeepsolution: a=a+b; b=a-b; a=a-b; example: a=2,b=3 a=2+3; (a=5) b=5-3; (b=2) a=5-2; (a=3) now a=3,b=2

JayCan also be done as:

NOTE: does not work if a or b is 0

Chaitanya Dwivedia = a+b b = a-b a = a-b

Example: a = 7 b = 3

Example: a = 7+3 = 10 b = 10-3 = 7 a = 10-7= 3

RaviYep, that's exactly the solution provided.

Cddca = (a + b)/2 b = a - b

a = a - b b = a + 2b

Another messy solution, but works.

AbhinavWhy think so uch , when you can use multiple assignment operators :| b=a+b-(a=b);

lalithaa=a+b-(b=a) this is single line swapping with out using third variable

Alex Pinkneyuse Python:

easy!