In this I will tell you how to do swapping of two numbers without using third variable in c. So , Without any further delay let's get started . In this we are going to use bitwise ^(XOR) operator .
Let us first understand the working of XOR(^) operator .
Truth Table
A B A^B
0 0 0
1 0 1
0 1 1
1 1 0
Now you have seen how this operator going to work . Let's us see code .
Code:
#include <iostream>
using namespace std;
int main()
{
int a = 5, b = 4;
cout << "Before doing swapping :" << endl;
cout << "a = " << a << " b = " << b << endl;
a = a ^ b; // here the value of a become 1 after doing operation
b = a ^ b; // here value of b become 5 after doing operation
a = a ^ b; // here value of a become 4 after doing operation
cout << "After doing swapping : " << endl;
cout << "a = " << a << " b = " << b << endl;
return 0;
}
Logic:
Let us understand what we are doing here . we have take two variable
a = 5 and b = 4 of type int . Then we print the values before swapping.
We all known that binary of 5 is 101 and 4 is 100 . When we first perform
XOR(^) on a and b it then value of a become in binary 001 i.e. 1.That is
easily understand by Truth table. Then we again perform this operation
now value of b become 5 (in binary 101) by doing XOR(^) of a and b .
Now we again do XOR(^) of a(is 001) and b(is 101) and value of a become 4(100).
Output:
Now we can see that our program work correctly. You can try this by taking input from the console . And can check its accuracy . It is
better than traditional third variable. And it is perform on bits so
it is faster than that .
I hope this is helpful to you in your work.
Thanks for reading.