There are 4 methods of swapping of numbers.
Method : 1
By using 3rd variable....
int a=10,b=20,c;c=a;
a=b;
b=c;
print(a,b); // Now a=20 and b=10
Method : 2
Without using 3rd variable....int a=10,b=20;
a=a+b;
b=a-b;
a=a-b;
print(a,b); // Now a=20 and b=10
Method :3
Using multiplication and division method....
int a=10,b=20;
a=a*b;
b=a/b;
a=a/b;
print(a,b); // Now a=20 and b=10
Method :4
Best method for swapping using XOR Gate
int a=10,b=20;
a=a^b;
b=a^b;
a=a^b;
print(a,b); // Now a=20 and b=10
Method 4 is best method for swapping. Because others are fail to swap in certain conditions like Method 3 is fail if value of int b is 0 and Method 2 is fail if addition or subtraction crosses to its maximum limit.
0 comments:
Post a Comment