In this program, we will learn how to swap two numbers using a temporary variable.
First, read two numbers from the keyboard. Display the numbers before swapping. Then swap the numbers using a temporary variable. Then display the swapped numbers.
Step 1: Read two numbers from standard input (keyboard).
Step 2: Print or display original numbers on standard output.
Step 3: In this step, we do the actual swapping of numbers.
Let, num1 be the first variable and num2 be the second variable. First, we store the value of the first variable into a temporary variable. Then the value of the first variable is stored in the second variable. Finally, the value of the temporary variable will be stored in the first variable.
Step 4: Display the swapped numbers.
Sample Input to the program:
Number 1 = 20
Number 2 = 30
Number 1 = 30
Number 2 = 20
Program to swap two numbers 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 ("First number is : ", num2) #Swapping using temporary variable temp = num1 num2 = num1 num1 = temp #Print Swapped number print ("After swapping") print ("First number is : ", num1) print ("First number is : ", num2)
Enter the first number: 20
Enter the second number: 30
First number is: 30
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