In C++, variables are containers that store data. Sometimes, we may need to swap the values of two variables. The traditional method involves using a third variable as a temporary storage to facilitate the swap. In this article, we will learn how to swap two variables using the XOR technique.
Example:
Input: a = 5; b = 10;
Output: a = 10; b = 5;
Swapping Two Variables Using XOR in C++
The XOR operator returns true if the number of true inputs is odd. To swap two variables using XOR in C++, wc can do it byBy performing the XOR operation on the two variables three times, we can swap their values without using a third variable. Here’s how it works:
C++ Program to Swap Two Variables Using XOR
C++ Program to Swap Two Variables Using XOR
// C++ Program to illustrate how to swap two variables // without using a third variable in C++. #include <iostream> using namespace std;
// main function int main()
{ // variable definition
int a = 2, b = 3;
// initial value
cout << "Before swapping the variables a= " << a
<< " b= " << b;
cout << endl;
// swapping logic
a = a + b;
b = a - b;
a = a - b;
// final value
cout << "After swapping the variables a= " << a
<< " b= " << b << endl;
return 0;
} |
Before swapping the variables a= 2 b= 3 After swapping the variables a= 3 b= 2
Time Complexity: O(1)
Space Complexity: O(1)