Swap Two Variables without Using Third Variable

It is very trivial to swap two variables with the help of another one. Here we’ll see how to do the same thing without using the third variable.

Solution 1:

    a=b+a;
    b=a-b;
    a=a-b;

Explanation: Here the principle is simple, if you have one variable and the summation of two variables you want to swap then you can get the other variable. In the first line we overrode the value of a with summation of the two variables. Now the b has its own value intact. In the second line b will get original value of a. Because in line 2 a had the summation of a and b, If we subtract b from summation, then we will get a. Now in third line b has the original starting value of a and a is the summation. So after assignment a will get the original value of b.

Problem with this solution: This solution works fine in most of the cases but will not work if the values of the variables are reasonably large such that the summation exceeds the maximum limit of a variable. Maximum limit of a variable depends on the data type of the variable. For example for signed int it is 2,147,483,647 and for unsigned int it is 4,294,967,295.

Solution 2: The above mentioned problem can be overcome with this solution.

    a=a^b;
    b=a^b;
    a=b^a;

Explanation: This solution is similar to the above. Instead of using summation, XOR (Exclusive Or) operation is used here. Principle is also same, if you have the value of one variable and the summation of two variables you want to swap, then you can get the other by using XOR operation.

There are many other solutions, here are few of them.

#include <studio.h>
int main(){
    int a=5,b=10;
//process one
    a=b+a;
    b=a-b;
    a=a-b;
    printf("a= %d  b=  %d",a,b);

//process two
    a=5;
    b=10;
    a=a+b-(b=a);
    printf("\na= %d  b=  %d",a,b);
//process three
    a=5;
    b=10;
    a=a^b;
    b=a^b;
    a=b^a;
    printf("\na= %d  b=  %d",a,b);
   
//process four
    a=5;
    b=10;
    a=b-~a-1;
    b=a+~b+1;
    a=a+~b+1;
    printf("\na= %d  b=  %d",a,b);
   
//process five
    a=5,
    b=10;
    a=b+a,b=a-b,a=a-b;
    printf("\na= %d  b=  %d",a,b);
    return 0;
}

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

Leave a Reply

Your email address will not be published. Required fields are marked *

0
0
0
0
0
0