C# Program to Swap Two Numbers using Bitwise XOR Operation

This is a C# Program to swap the contents of two numbers using bitwise xor operation.

Problem Description

This C# Program Swaps the Contents of two Numbers using Bitwise XOR Operation.

Problem Solution

Take two inputs from the user and perform Bitwise XOR Operation as shown in the program below.

Program/Source Code

Here is source code of the C# Program to Swap the Contents of two Numbers using Bitwise XOR Operation. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to Swap the Contents of two Numbers using Bitwise XOR Operation
 */
using System;
class program
{
    public static void Main()
    {
        int i, k;
        Console.WriteLine("Enter two integers \n");
        i = int.Parse(Console.ReadLine());
        k = int.Parse(Console.ReadLine());
        Console.WriteLine("\n Before swapping i= {0} and k = {1}", i, k);
        i = i ^ k;
        k = i ^ k;
        i = i ^ k;
        Console.WriteLine("\n After swapping i= {0} and k = {1}", i, k);
        Console.ReadLine();
    }
}
Program Explanation

In this C# Program, we are reading two integers using ‘i’ and ’k’ integer variables. The bitwise XOR operation is used between ‘i’ and ‘k’ integer variable values. Assign the value to ‘i’ variable and perform the bitwise XOR operation. And assign the value to ‘k’ variable and again to ‘i’ variable. Print the contents of two numbers using bitwise XOR operation.

advertisement
advertisement
Runtime Test Cases
 
Enter two integers
23
34
Before swapping i= 23 and k = 34
After swapping i= 34 and k = 23

Sanfoundry Global Education & Learning Series – 1000 C# Programs.

If you wish to look at all C# Programming examples, go to 1000 C# Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.