Python Program to find swap two numbers without temp variable (Addition and Subtraction Method)
Program
a = int(input("Enter the value of a:\t"))
b = int(input("Enter the value of b:\t"))
print("Values before swapping:")
print("a:\t{}\nb:\t{}".format(a,b))
a = a + b
b = a - b
a = a - b
print("Values after swapping:")
print("a:\t{}\nb:\t{}".format(a,b))
This program swaps two numbers without using a temporary variable by using addition and subtraction.
a = int(input("Enter the value of a:\t"))
b = int(input("Enter the value of b:\t"))
- The user inputs two numbers (
a
andb
). input()
takes input as a string, andint()
converts it to an integer.
print("Values before swapping:")
print("a:\t{}\nb:\t{}".format(a,b))
- Displays the original values before swapping.
Swapping Logic Using Addition and Subtraction
a = a + b # Step 1: Store the sum of a and b in a
b = a - b # Step 2: Subtract b from the new value of a, which gives original a and assigns it to b
a = a - b # Step 3: Subtract new b (original a) from new a (sum), which gives original b and assigns it to a
- The sum of both numbers is stored in
a
. - Then
b
is updated toa - b
, effectively givingb
the value ofa
before swapping. - Finally,
a
is updated toa - b
, effectively givinga
the value ofb
before swapping.
print("Values after swapping:")
print("a:\t{}\nb:\t{}".format(a,b))
- Prints the swapped values.
Key Takeaways
- Swaps two numbers without using a temporary variable.
- Uses basic arithmetic operations (addition and subtraction).
- Works efficiently for small values but may cause overflow issues for very large numbers in some languages.
Output
Enter the value of a: 12
Enter the value of b: 3
Values before swapping:
a: 12
b: 3
Values after swapping:
a: 3
b: 12