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

18 July 2012

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


 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:

Swap 2 numbers using temp/third variable
 


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:
Swap 2 numbers without using temp/third variable

0 Comments:

Post a Comment