Python program to swap two numbers without using a temporary variable

 

Problem Definition:

In this program, we will learn how to swap two numbers without using a temporary variable.

Logic of the program:

First, read two numbers from the keyboard. Display the numbers before swapping. Then swap the numbers without using a temporary variable. Then display the swapped numbers.

Steps (Algorithm):

Step 1: Read two numbers from standard input (keyboard). Say number 1 and number 2.

Step 2: Print or display original numbers (number 1 and number 2) on standard output.

Step 3: In this step we do the actual swapping of number without using temporary variable.

Let, number 1 be the first variable with value 20 and number 2 be the second variable with value 30.

Number 1 = Number 1 + Number 2

#Number 1 is 20 + 30 = 50

Number 2 = Number 1 – Number 2

#Number 2 is 50 – 30 = 20

Number 1 = Number 1 – Number 2

#Number 1 is 50 – 20 = 30

First, we add the value of the first variable to a second variable and store it in the first variable that is in number 1. Then we subtract the value of the second variable from the first variable and store the result in the second variable. Finally, we again subtract the value of the second variable from the first variable and store the result in the first variable.

Step 4: Display the swapped numbers.

Sample Input to the program:

Number 1 = 20

Number 2 = 30

Expected Output:

Number 1 = 30

Number 2 = 20

Program to swap two numbers without using a temporary variable:

#Python program to swap numbers using temporary variable
num1 = int (input ("Enter the first number: "))
num2 = int (input ("Enter the second number: ")) 

#Print original number
print ("Before swapping")
print ("First number is : ", num1)
print ("The Second number is : ", num2) 

#Swapping without using temporary variable
num1 = num1 + num2
num2 = num1 - num2
num1 = num1 - num2

#Print Swapped number
print ("After swapping") 
print ("First number is : ", num1)
print ("The Second number is : ", num2) 

Output:

Before Swapping

Enter the first number: 20

Enter the second number: 30

After Swapping

First number is: 30

The second number is: 20

The above programs deal with how to swap two numbers using a temporary variable. For more such programs do visit this website regularly. Also, do my Facebook page for regular updates – Click here to follow my Facebook page

Leave a Comment

Your email address will not be published. Required fields are marked *