C# program to swap numbers using XOR operator

    a = a^b;
    b = a^b;
    a = a^b;

Program:

using System;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 0;
            int b = 0;
            
            //reading numbers
            Console.Write("Enter first number: ");
            a = int.Parse(Console.ReadLine());
            Console.Write("Enter second number: ");
            b = int.Parse(Console.ReadLine());

            //printing the numbers before swapping
            Console.WriteLine("Before swapping...");
            Console.WriteLine("a = {0} \t b = {1}", a, b);

            //swapping 
            a = a ^ b;
            b = a ^ b;
            a = a ^ b;

            //printing the numbers after swapping
            Console.WriteLine("After swapping...");
            Console.WriteLine("a = {0} \t b = {1}", a, b);

            //hit ENTER to exit
            Console.ReadLine();
        }
    }
}


Output

Enter first number: 100
Enter second number: 200
Before swapping...
a = 100          b = 200
After swapping...
a = 200          b = 100

Leave a Comment

error: Alert: Content is protected!!