Given two integers, swap them without using any third variable.

Method 1: Using addition and subtraction operator

Download  Run Code

 
Note that a copy of the actual parameter address is passed in a pass by reference, and any changes made to these variables in the function will affect the original. This can also be achieved using pointers in C, as demonstrated below.

Download  Run Code

Method 2: Using multiplication and division operator

Download  Run Code

Method 3: Using Bitwise XOR operator

Download  Run Code

Method 4: Using difference between two values

Download  Run Code

Method 5: Using single line expressions

We can also use any of the following expressions to swap two variables in a single line:

  • x = x ^ y ^ (y = x);
  • x = x + y – (y = x);
  • x = (x × y) / (y = x);

The following C++ program demonstrates it:

Download  Run Code