Hello Learner
Contributor
Stats
 Views : 19283 Comments : 0 Rating : 0
Actions

# swapping two variables without using temp/third variable and using temp/third variable in .NET

By Ashok Nalam on 21 Dec 2012 | Category: C# | Tagged: variable swap
In this snippet we will see how swap two variables without using temp/third variable and using temp/third variable in .NET.
 Rate this resource

In many of interviews, interviewers will ask write a program to swap two numbers without using a third variable or temporary (temp) variable. So in this snippet we will see how to swap two numbers with/without using third variable.

#### Program : Swapping 2 numbers With temp variable

`class SwapTwoNumbersUsingTempVariable    {        public static void Main()        {            Console.WriteLine("/****** Program to swap 2 numbers using temporary variable *******/");            int a = 10, b = 20;            Console.WriteLine(" Values before swapping a={0} , b={1}", a, b);            int tempVar = 0; //temporary variable            tempVar = a;            a = b;            b = tempVar;            Console.WriteLine(" Values after swapping a={0} , b={1}", a, b);            Console.ReadKey();        }    }`

#### Program : Swapping 2 numbers Without temp variable

`class SwapTwoNumbersWithoutUsingThirdVariable    {        public static void Main()        {            Console.WriteLine("/****** Program to swap 2 numbers without using temporary variable *******/");            int a = 10, b = 20;            Console.WriteLine(" Values before swapping a={0} , b={1}", a, b);            a = a + b;            b = a - b;            a = a - b;            Console.WriteLine(" Values after swapping a={0} , b={1}", a, b);            Console.ReadKey();        }    }`

#### Output:

 Rate this resource