Q:

C# program to swap numbers using XOR operator

belongs to collection: C# Basic Programs | basics

0

Given two integer numbers and we have to swap them using XOR operator in C#.

Statements to swap two numbers using XOR operator,

If the variables are a and b, then the following XOR statements are used to swap their values:

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

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | basics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to find the magnitude of an integer num... >>
<< C# | print type, max and min value of various data...