In C++, you can swap two variables without using extra variables using the same arithmetic or bitwise XOR methods. Here's how you can do it:
1. Using Arithmetic Operations:
#include <iostream>
using namespace std;
int main() {
int a = 5, b = 10;
a = a + b; // Step 1: a becomes 15 (5 + 10)
b = a - b; // Step 2: b becomes 5 (15 - 10)
a = a - b; // Step 3: a becomes 10 (15 - 5)
cout << "a = " << a << ", b = " << b << endl;
return 0;
}
2. Using Bitwise XOR:
#include <iostream>
using namespace std;
int main() {
int a = 5, b = 10;
a = a ^ b; // Step 1: a becomes 15 (binary XOR of 5 and 10)
b = a ^ b; // Step 2: b becomes 5
a = a ^ b; // Step 3: a becomes 10
cout << "a = " << a << ", b = " << b << endl;
return 0;
}