Program for swapping of two numbers
Swapping refers to the exchange of two or more things.
Example:
a=5 , b=10
After swapping a becomes 10 and b becomes 5.
Explanation :
Read a and b value.
Use any of the below methods and get output
Method1:
We have very simple method in python i.e.,
a , b = b , a
Method2:
Using third variable or temporary variable ,
a = a + b b = a - b a = a- b
Method3:
Using Bitwise XOR (^),
a = a ^ b b = a ^ b a = a ^ b
Input :
a = 5
b = 10
Output :
a = 10
b = 5
PROGRAM IN PYTHON
#swapping of two numbers
a = 5
b = 10
a , b = b , a
#after swapping
print("a is",a,"b is ",b)
#method 2
a = a + b
b = a - b
a = a - b
print("a is",a,"b is ",b)
#method 2 --- using xor
a = a ^ b
b = a ^ b
a = a ^ b
print("a is",a,"b is ",b)
Output
a is 10 b is 5
a is 5 b is 10
a is 10 b is 5
Comments
Post a Comment
Type Your Comments !
Please do not enter any spam link in the comment box.