Question 15 of 22intermediate🔧 ApplyLong Answer4 marks

Write a program to swap two numbers without using a third variable.

Correct Answer

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

Exercise: EXERCISE | Q: 15 | (Page 32)
For More Understanding

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

  1. Step 1: Accept two integer inputs from user using int(input()) function

  2. Step 2: Display original values before swapping

  3. Step 3: Calculate num1 = num1 + num2 (stores sum in num1)

  4. Step 4: Calculate num2 = num1 - num2 (num2 now holds original num1 value)

  5. Step 5: Calculate num1 = num1 - num2 (num1 now holds original num2 value)

  6. Step 6: Display swapped values as output