Given the two numbers a and b stored in variables x and y, respectively. How can we swap values of variables x and y without using any third variable like shown below:
Input: x = 2 , y = 3
Output: x = 3 , y = 2
This problem can be solved by the algorithm below:
Step 1: Take two variables x
and y
.
Step 2: Store the sum of these variables in x.
Step 3: Subtract y from x and store it in y.
Step 4: Replace x with x - y.
As a result, variables x and y have been swapped.
Numerically it can be written as:
x = x + y
y = x - y
x = x - y
Let’s understand the working of this algorithm with the help of an example in the illustration provided below:
The limitations of the approach above are as follows:
x = x + x ⇒ x = 2x
x = x - x ⇒ x = 2x - 2x = 0
x = x - x ⇒ x = 0 - 0 = 0
So, it will always result in 0.
To solve the second limitation, there is a very simple solution. Add a check at the start of the swap function that if both variables are the same, then don’t swap:
if (x == y)
{
// return without swapping
return;
}
The C++ implementation of the mentioned algorithm is as follows:
//Self explanatory code for swapping two numbers x and y#include <iostream>using namespace std;void swap(int &x, int &y) //Function to swap x and y{if( x == y ){return;}x = x + y ; //Step 2y = x - y ; //Step 3x = x - y ; //Step 4}int main(){int x = 2, y = 3; //Initializationcout<<"Before Swapping: x = "<<x<<" and y = "<<y<<endl;swap ( x , y ) ; //Function callingcout<<"After Swapping: x = "<<x<<" and y = "<<y<<endl;return 0 ;}
This way, we can swap two numbers without using any temporary variable.
Free Resources