Home » C# programs » C# basic programs

C# program to swap numbers using XOR operator

C# program for swapping two numbers using XOR operator: Given two numbers and we have to swap them.
Submitted by IncludeHelp, on February 26, 2019

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;

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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.