Our Feeds

Saturday, 26 July 2014

Ajith KP

Swap values of variables without using intermediate variable

          Swap values of variables is basic practical question for programming beginners. It is very easy and usually we are doing it using a 3rd variable to store value temporary.



Algorithm by using 3rd variable:

tempVar = firstVar;
firstVar = secondVar;
secondVar = tempVar;

Now for a change one asks to you to do it by without using a 3rd variable. This question made a brain storm when I was studying basics of C programming. My wild thoughts didn't give the answer for first 1 minute. I would like to share the code.


#include <iostream>
using namespace std;
int main()
{
    int a, b;
    a = 10;     // variable `a` gets value of 10
    b = 20;     // variable `b` gets value of 20
    cout<<"Before swap, a : "<<a<<", b: "<<b<<endl;
    a = a+b;    // now `a` is 10 + 20 = 30
    b = a-b;    // now `b` is 30 - 20 = 10
    a = a-b;    // now `a` is 30 - 10 = 20 -----> Swapped values
    cout<<"After swap, a : "<<a<<", b : "<<b<<endl;
}