Python Program to find swap two numbers without temp variable (Multiplication and Division Method)

Program

a = int(input("Enter the value of a:\n"))
b = int(input("Enter the value of b:\n"))
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 multiplication and division.

a = int(input("Enter the value of a:\n"))
b = int(input("Enter the value of b:\n"))
  • The user inputs two numbers (a and b).
  • input() takes input as a string, and int() 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 Multiplication and Division

a = a * b  # Step 1: Store the product of a and b in a
b = a / b  # Step 2: Divide new a (product) by b to get original a and assign it to b
a = a / b  # Step 3: Divide new a (product) by new b (original a) to get original b and assign it to a
  • The product of both numbers is stored in a.
  • Then b is updated to a / b, effectively giving b the value of a before swapping.
  • Finally, a is updated to a / b, effectively giving a the value of b 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 multiplication and division.
  • This method does not work if one of the numbers is zero since division by zero is not allowed.
  • It may cause precision errors for non-integer values.

Output 1

Enter the value of a:
66
Enter the value of b:
12
Values before swapping:
a:	66
b:	12
Values after swapping:
a:	12
b:	66