Write a program to swap two numbers using a third variable.
Question
Write a program to swap two numbers using a third variable.
✨ Free AI Tools for You
Powered by Chatterbot AI
Answer
Here's a simple Python program to swap two numbers using a third variable:
# Program to swap two numbers using a third variable
# First, we define the numbers to be swapped
num1 = 5
num2 = 10
# We print the numbers before swapping
print("Before swapping:")
print("num1 =", num1)
print("num2 =", num2)
# We use a third variable to hold the value of num1 temporarily
temp = num1
num1 = num2
num2 = temp
# We print the numbers after swapping
print("After swapping:")
print("num1 =", num1)
print("num2 =", num2)
Output:
Before swapping:
num1 = 5
num2 = 10
After swapping:
num1 = 10
num2 = 5
This program demonstrates the use of a third variable to temporarily hold the value of one variable while assigning the value of the other variable, achieving the swap.
India's 1st AI Doubt Solver for CBSE, JEE, and NEET
Ask a Question for Freeand then it's just ₹212 a month