Objects in this mirror are closer to Microsoft Technologies. DNM objective is to help users on Microsoft technologies by providing Articles, snippets, Interview Questions.

25 July 2012

swapping three variables without using temp/fourth variable in C#.NET

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

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

Output:
Values before swapping a=10 , b=20 , c=30
Values after swapping a=30 , b=10, c=20

0 Comments:

Post a Comment