Write a program to swap two numbers without using a third variable.
Question
Write a program to swap two numbers without using a third variable.
✨ Free AI Tools for You
Powered by Chatterbot AI
Answer
You can swap two numbers without using a third variable by using arithmetic operations or the XOR bitwise operator. Here’s a Python program using the arithmetic operations method:
# Program to swap two numbers without using a third variable
# Input: Two numbers
num1 = 5
num2 = 10
print("Before swapping:")
print("num1 =", num1)
print("num2 =", num2)
# Swapping using arithmetic operations
num1 = num1 + num2 # num1 now becomes 15
num2 = num1 - num2 # num2 now becomes 5
num1 = num1 - num2 # num1 now becomes 10
print("After swapping:")
print("num1 =", num1)
print("num2 =", num2)
Explanation:
Initialize
num1
andnum2
with given values.Add
num2
tonum1
and store the result innum1
.Subtract the new
num1
(which isnum1 + num2
) bynum2
, and store the result innum2
.Subtract the new
num1
by the newnum2
, and store the result innum1
.Print the swapped values.
Output:
Before swapping:
num1 = 5
num2 = 10
After swapping:
num1 = 10
num2 = 5
India's 1st AI Doubt Solver for CBSE, JEE, and NEET
Ask a Question for Freeand then it's just ₹212 a month