C++ Program to Swap Two Numbers Using Bitwise Operator
/*C++ Program to Swap Two Numbers Using Bitwise Operator*/
#include<iostream>
using namespace std;
int main()
{
int a,b,t;
a=10;
b=20;
t=a^b;
b=b^t;
a=t^b;
cout<<"a="<<a<<" b="<<b;
return 0;
}
OUTPUT:
a=20 b=10
EXPLANATION:
When t=a^b
statement is executing, XOR operation between variable a (value 10) and b (value
20) is performed and result is stored in variable t. Result of XOR between 10
and 20 is 30, thus 30 is stored in variable t.
When b=b^t
statement is executing, XOR operation between b (value 20) and t (value 30) is
performed and result is stored in variable b. Result of XOR between 20 and 30
is 10, thus 10 is stored in variable b.
When a=t^b statement is executing, XOR operation between t (value 30)
and b (value 10) is performed and result is stored in variable a. Result of XOR
between 30 and 10 is 20, thus 20 is stored in variable a.
Then, value of a and b is print on monitor using cout statement.
C++ Program to Swap Two Numbers Using Bitwise Operator Without Third Variable.
/*C++ Program to Swap Two Numbers Using Bitwise Operator Without Third Variable*/
#include<iostream>
using namespace std;
int main()
{
int a,b;
a=10;
b=20;
a=a^b;
b=a^b;
a=a^b;
cout<<"a="<<a<<" b="<<b;
return 0;
}
OUTPUT:
a=20 b=10
0 comments:
Post a Comment