Pages

Friday, May 10, 2013

C#: Swapping two numbers without temporary variable

Following program explains, how to swap two numbers without using temporary variable.
Have you ever thought of swapping to variables like so? easy to do with simple addition
and subtraction between two numbers.
//function for swapping two numbers
public void swap(int a, int b)
        {
//value of a and b before swapping
            Console.WriteLine("The value a and b before swapping: a=" + a + " and b " + b);
//if,a=3 and b=5
//a=3+5=8
//b=5
            a = a + b;
//now, b=8-5=3
//a=8, now b got a's value
            b = a - b;
//a=8-3=5
//so a=5,b=3 without using any temp var
            a = a - b;
            Console.WriteLine("The value a and b before swapping: a="+a+" and b "+b);
  }

//input: a=3, b=5
Output: a=5, b=3

No comments:

Post a Comment