Write a program to swap two numbers without using a third variable.
Program to swap two numbers without using a third variable
num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: "))
print("Before swapping:") print("num1 =", num1) print("num2 =", num2)
Swapping without third variable using arithmetic operations
num1 = num1 + num2 num2 = num1 - num2 num1 = num1 - num2
print("After swapping:") print("num1 =", num1) print("num2 =", num2)
Output: Enter first number: 10 Enter second number: 20 Before swapping: num1 = 10 num2 = 20 After swapping: num1 = 20 num2 = 10
Explanation
This question tests the student's understanding of arithmetic operators and variable manipulation. The program uses addition and subtraction operations to swap values without creating a temporary variable. The logic works as follows: first, num1 stores the sum of both numbers; then num2 is calculated by subtracting the original num2 from the sum (giving original num1); finally, num1 is calculated by subtracting the new num2 from the sum (giving original num2). This technique demonstrates efficient memory usage and understanding of operator precedence.
Solution Steps
Step 1: Accept two integer inputs from user using int(input()) function
Step 2: Display original values before swapping
Step 3: Calculate num1 = num1 + num2 (stores sum in num1)
Step 4: Calculate num2 = num1 - num2 (num2 now holds original num1 value)
Step 5: Calculate num1 = num1 - num2 (num1 now holds original num2 value)
Step 6: Display swapped values as output