Sunday, November 21, 2010

How to swap two variables without using a third variable ?

#include <stdio.h>
int main()
{
    int m=10,n=15;
    printf(“Before swapping: m=%d, n=%d\n”,m,n);
    m=m^n;
    n=n^m;
    m=m^n;
    printf(“After swapping: m=%d, n=%d\n”,m,n);
    return 0;
}

Explanation:

The operator here used is (^) bit wise exclusive OR operator.  The truth table of exclusive OR is as:

Operator 1
Operator 2
Output
0
0
0
0
1
1
1
0
1
1
1
0


Convert the numbers from decimal system to binary system and then apply the logic.

Advantage:

It does not occupy a third variable and hence memory consumption is less. This is more advantageous while swapping two strings. The strings occupy memory a lot. Copying one string to other takes CPU cycles as well. Using pointer and union we can optimize both memory and CPU cycle consumption.
Refer below program:

//Program by Nikunj Master, Eleiss
#include<stdio.h>
#include<stdlib.h>

union memory
{
        char *ptr;
        int addr;
};

int main()
{
        union memory m1,m2;
        m1.ptr=(char*)malloc(100*sizeof(char));
        m2.ptr=(char*)malloc(100*sizeof(char));
        printf("Scan two strings\n");
        scanf("%s %s",m1.ptr,m2.ptr);
        printf("Before swapping: m1=%s, m2=%s\n",m1.ptr,m2.ptr);
        m1.addr=m1.addr^m2.addr;
        m2.addr=m2.addr^m1.addr;
        m1.addr=m1.addr^m2.addr;
        printf("After swapping: m1=%s, m2=%s\n",m1.ptr,m2.ptr);
        return 0;
}

No comments:

Post a Comment