[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:

 

private static void 

SwapUsingMultiplyDivideOperator()
        {
            int num1 = 7, num2 = 9;
            Console.WriteLine("Before swapping: 

num1={0}, num2={1}", num1, num2);
            num1 = num1 * num2;
            num2 = num1 / num2;
            num1 = num1 / num2;
            
            Console.WriteLine("After swapping: 

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

 

 

 

4. Witout using third variable and with help of bitwise XOR(^) operator:


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

num1={0}, num2={1}", num1, num2);
            num1 = num1 ^ num2;
            num2 = num1 ^ num2;
            num1 = num1 ^ num2;

            Console.WriteLine("After swapping: 

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

And swapping two variables in T-SQL (TSQL):


declare @num1 int=7, @num2 int=9;
--select 'Before swapping num1=' + CAST(@num1 as varchar) + ', num2=' + CAST(@num2 as varchar)
print 'Before swapping'
select @num1 as Num1, @num2 as Num2
select @num1=@num1+@num2, @num2=@num1-@num2, @num1=@num1-@num2
print 'After swapping'
select @num1 as Num1, @num2 as Num2

blog comments powered by Disqus

Posts By Month