In this pseudocode we will swap the values of two variables using a temporary variable. Here, Let’s learn how to swap values of two integer variables.
Pseudocode Swap to Numbers with Entered by the User
First example, swap two variables without taking value from user.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
BEGIN #define variables and assing values to variables NUMBER num1=10, num2=15, temp #assign num1 to temp temp=num1 #assing num2 to num1 num1=num2 #assign temp to num2 num2=temp OUTPUT "number 1:"+num1 OUTPUT "number 2:"+num2 END |
FlowChart:

Flowchart of pseudocode to swap to variables
Java Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public static void main(String[] args) { float first = 2.2f, second = 10.4f; System.out.println("--Before swap--"); System.out.println("First number = " + first); System.out.println("Second number = " + second); first = first - second; second = first + second; first = second - first; System.out.println("--After swap--"); System.out.println("First number = " + first); System.out.println("Second number = " + second); } |
Pseudocode Swap to Numbers without Entered by the User
Second example, swap two variables with taking value from user.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
BEGIN #define variables and assing values to variables NUMBER num1, num2, temp #take numbers from user INPUT num1 INPUT num2 #assign num1 to temp temp=num1 #assing num2 to num1 num1=num2 #assign temp to num2 num2=temp2 PRINT "number 1:"+num1 PRINT "number 2:"+num2 END |
C++ Code: Write a program to swap two numbers in C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
using namespace std; #include<iostream> int main() { int a,b,temp; cout<<"Enter the value of a: "; cin>>a; cout<<"Enter the value of b : "; cin>>b; temp = a; a = b; b = temp; cout<<"a : "<<a<<endl; cout<<"b : "<<b<<endl; cout << "Press a key to continue ..." << endl; cin.ignore(); cin.get(); return EXIT_SUCCESS; } |
Python Code:Write a program to swap two numbers in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# Python program to swap two variables # To take input from the user x = input('Enter value of x: ') y = input('Enter value of y: ') # create a temporary variable and swap the values temp = x x = y y = temp print('The value of x after swapping: {}'.format(x)) print('The value of y after swapping: {}'.format(y)) |
In this example you have learned how to swap to variables using third variable with pseudoce code and programming codes.
[…] This link to see the sample(s) […]