[X]

C# - Swapping values of two variables without using third variable

 

 

Lots of guys are asked and have delved into solving a very common question - How do you swap values of two variables without using third variable?

Well there are more than one ways, we could achieve it.

So first let's start from school days.

1. using 3rd variable:

 

class Program
    {
        static void Main(string[] args)
        {
            SwappingUsingThirdVariable();
        }

        private static void SwappingUsingThirdVariable()
        {
            int num1=7, num2=9, num3=0;
            Console.WriteLine("Before swapping: num1={0}, num2={1}", num1, num2);
            num3 = num1; num1 = num2; num2 = num3;
            Console.WriteLine("After swapping: num1={0}, num2={1}", num1, num2);
            Console.ReadLine();
        }
    }

 

 


2. Witout using third variable and with help of plus/minus (+,-) operator: 

 

private static void SwappingUsingPlusMinusOperator()
        {
            int num1 = 7, num2 = 9;
            Console.WriteLine("Before swapping: 

num1={0}, num2={1}", num1, num2);
            if (num1 > num2)
            {
                num1 = num1 + num2;
                num2 = num1 - num2;
                num1 = num1 - num2;
                
            }
            else
            {
                num2 = num2 + num1;
                num1 = num2 - num1;
                num2 = num2 - num1;
                
            }
            Console.WriteLine("After swapping: 

num1={0}, num2={1}", num1, num2);
            Console.ReadLine();
        }

 

 

3. Witout using third variable and with help of mulitply/divide(*,/) operator:More...

Posts By Month