Monday, January 09, 2012

how to Swap two variables without using third variable

There are many way to swap two variables without using third variable


#include<stdio.h>

void swapOne(int a,int b)
{
   a=a^b;
   b=a^b;
   a=b^a;
}
void swapTwo(int a,int b)
{
   a=b-~a-1;
   b=a+~b+1;
   a=a+~b+1;
}
void swapThree(int a,int b)
{
    a=b+a;
    b=a-b;
    a=a-b;
}
void swapFour(int a,int b)
{
   a=a+b-(b=a);
}

void swapFive(int a, int b)
{
  a=b+a;
  b=a-b;
  a=a-b;
}

int main(){
    int a=5,b=3;
    //Two swap two variable call
     swapOne(a,b);
     or swapTwo(a,b);
     or swapThree(a,b);
     or swapFour(a,b);
     or swapFive(a,b);

     printf("%d %d\n",a,b);
    return 0;
}

No comments:

Post a Comment