General programming: Swapping 2 values without declaring a 3rd variable.

Discussion in 'Programming' started by Sapphiro, Oct 10, 2009.

  1. #1
    Hi all, I just learnt about a good algorithm to swap 2 variable values without calling an extra 3rd variable, I think it's good so I'm sharing it with everybody here. :p



    Scenario: Swap integer A and B

    Normally, programmers will probably do this..
    
    int a= 1;
    int b= 2;
    int c= 0;
    c= a;   --> c=1
    a= b;   --> a=2
    b= c;   --> b=1 (swapped, but int c is declared just to be a 'dummy' for the swap algorithm)
    
    Code (markup):

    For a cleaner coding, you can just do this.

    
    
    int a=1;
    int b=2;
    a= a+b; --> a= 3
    b= a-b; --> b = 3-2 = 1
    a= a-b; --> a= 3-1 = 2 (Swapped done)
    
    Code (markup):

    The algorithm's just as simple as that. ;)
     
    Sapphiro, Oct 10, 2009 IP
  2. mytheory

    mytheory Well-Known Member

    Messages:
    159
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    103
    #2
    great.. very tricky..
    i'm newbie on C programming. i'm still learning about if and loop ,
    but on my exercise on C, i rarely meet 'swap' , sometimes it is needed, but just for a better understanding about theory of variable.

    what is the other benefits of swap?
     
    mytheory, Oct 10, 2009 IP