In this C# program, we will learn how to write a program to swap two numbers using the XOR operator.
Here is the code of the program to swap two numbers using the XOR operator:
using System;
namespace TutorialsrackPrograms
{
class Program
{
//C# Program to Swap two Numbers using XOR Operator.
static void Main(string[] args)
{
int a = 0, b = 0;
Console.Write("Enter The First Number: ");
a = int.Parse(Console.ReadLine());
Console.Write("Enter The Second Number: ");
b = int.Parse(Console.ReadLine());
//Printing the Numbers Before Swapping
Console.WriteLine("Numbers Before Swapping ...");
Console.WriteLine("a = {0} \t b = {1}", a, b);
//Swapping Occurs Here
a = a ^ b;
b = a ^ b;
a = a ^ b;
//Printing the Number After Swapping
Console.WriteLine("Numbers After swapping...");
Console.WriteLine("a = {0} \t b = {1}", a, b);
Console.Read();
}
}
}
Enter The First Number: 5
Enter The Second Number: 10
Numbers Before Swapping ...
a = 5 b = 10
Numbers After swapping...
a = 10 b = 5
Comments