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

C# program to swap two variables using x-or operation can be implemented by using a bit-wise operator like x-or. Swapping of two numbers means the exchanging of values between them.






1. C# Program & output to swap two variables using X-Or operation

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

using System;

namespace Swap {
    class Program {
        static void Main(string[] args) {
            //declare and initialize variables
            int num1 = 5, num2 = 10;

            //show numbers before swapping
            Console.WriteLine("Before swapping: number1 = " + num1 + " and number2 = " + num2);

            //do swapping using xor(^)
            num1 = num1 ^ num2;
            num2 = num1 ^ num2;
            num1 = num1 ^ num2;

            //show numbers after swapping
            Console.WriteLine("After swapping: number1 = " + num1 + " and number2 = " + num2);

            // wait for user to press any key
            Console.ReadKey();
        }
    }
}

Output


Before swapping: number1 = 5 and number2 = 10

After swapping: number1 = 10 and number2 = 5