C++ Program to Swap Two Variables Using X-OR Operation

C++ program to swap two variables using X-OR operation can be designed by using bit-wise x-or operator (^). Swapping of two numbers means the exchanging of values between them.






1. C++ Program & output for swapping two variables using X-OR

Code has been copied
/********************************************
            alphabetacoder.com
C++ program to swap two numbers without third
variable but using bit-wise X-OR operator
*********************************************/
#include <iostream>

using namespace std;

int main() {
    int num1, num2;
    // take input of two numbers 
    cout << "Enter two numbers = ";
    cin >> num1;
    cin >> num2;

    cout << "Before swapping: number1 = " << num1 << " number2 = " << num2 << "\n";

    //do swapping using X-OR (^)
    num1 = num1 ^ num2;
    num2 = num1 ^ num2;
    num1 = num1 ^ num2;

    cout << "After swapping: number1 = " << num1 << " number2 = " << num2 << "\n";
    return 0;
}

Output


Enter two numbers = 5 2

Before swapping: number1 = 5 and number2 = 2

After swapping: number1 = 2 and number2 = 5