Write a program to swap two numbers using a third variable.
Program to swap two numbers 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 using a third variable
temp = num1 num1 = num2 num2 = temp
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 variable assignment and the concept of swapping values. The program uses a third variable (temp) to temporarily store the value of the first number before overwriting it. The swapping logic follows three steps: (1) store num1 in temp, (2) assign num2 to num1, and (3) assign temp to num2. This ensures both values are exchanged without any data loss. The context shows similar Python programs using input(), int() for type conversion, and print() statements for output.
Solution Steps
Step 1: Accept two integers from user using int(input())
Step 2: Display the original values before swapping
Step 3: Store the value of num1 in a temporary variable 'temp'
Step 4: Assign the value of num2 to num1
Step 5: Assign the value of temp (original num1) to num2
Step 6: Display the swapped values