How to swap two numbers without taking third variable in C#

Swapping two numbers is an easy task by taking a third variable as temporary. But when asked not to use any third variable some person may think that how it can be done. Although it is easy too. Let us take a look how you can achieve this :

SwapNumbers




using System;

namespace CommonAskedquestion
{
    class Program
    {
        static void Main(string[] args)
        {
            int a, b;
            Console.Write("Enter First number  : ");
            a = Convert.ToInt32(Console.ReadLine());

            Console.Write("Enter Second number : ");
            b = Convert.ToInt32(Console.ReadLine());

            Swap(a,b);           
            Console.ReadKey();
        }

        /// <summary>
        /// Swap two numbers without taking 3rd variable
        /// </summary>
        private static void Swap(int a, int b)
        {
            Console.WriteLine("Before Swapping");
            Console.WriteLine("a = " + a);
            Console.WriteLine("b = " + b);

            a = a + b;
            b = a - b;
            a = a - b;

            Console.WriteLine("After Swapping");
            Console.WriteLine("a = " + a);
            Console.WriteLine("b = " + b);
        }
    }
}