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. 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.
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?