Saturday 28 February 2015

How to Swap two variables without using third variable

Solution 1

#include<iostream>
using namespace std;
void main()
{
int a=5,b=10;
a=b+a;
    b=a-b;
    a=a-b;
cout<<"a =  "<<a<<"\tb =  "<<b;

}

Solution 2

#include<iostream>
using namespace std;
void main()
{
int a=5,b=10;
    a=5;
    b=10;
    a=a+b-(b=a);
cout<<"a =  "<<a<<"\tb =  "<<b;

}

Solution 3

#include<iostream>
using namespace std;
void main()
{
int a=5,b=10;
    a=a^b;
    b=a^b;
    a=b^a;
cout<<"a =  "<<a<<"\tb =  "<<b;

}

Solution 4

#include<iostream>
using namespace std;
void main()
{
int a=5,b=10;
    a=b-~a-1;
    b=a+~b+1;
    a=a+~b+1;
cout<<"a =  "<<a<<"\tb =  "<<b;

}

Solution 5

#include<iostream>
using namespace std;
void main()
{
int a=5,b=10;
        a=b+a,b=a-b,a=a-b;
cout<<"a =  "<<a<<"\tb =  "<<b;

}



If You Enjoyed This, Take 5 Seconds To Share It