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();
}
}
output:
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: