Friday, 2 October 2015

Swap two numbers without using a third variable

How to swap two numbers using third variable ?? 

Here are five different ways of doing it..

void main(){
int a=5,b=10;

//#1
a=b+a;
b=a-b;
a=a-b;
printf("a= %d, b= %d\n",a,b);

//#2
a=5;
b=10;
a=a+b-(b=a);
printf("a= %d, b= %d\n",a,b);

//#3
a=5;
b=10;
a=b-~a-1;
b=a+~b+1;
a=a+~b+1;

printf("a= %d, b= %d\n",a,b);

//#4
a=5;
b=10;
a=a^b;
b=a^b;
a=b^a;

printf("a= %d, b= %d\n",a,b);

#5
a=5;
b=10;
a=b+a,b=a-b,a=a-b;

printf("a= %d, b= %d\n",a,b);


}
Note: Please note carefully the difference between #1 and #5.


No comments:

Post a Comment