Swap the Values of Two Variables

Learn to write pseudocode and create a flowchart for swapping the values of two variables.

Problem statement

You have two variables n1 and n2 containing two numbers, and you want to swap the values that they hold.

The main steps in problem-solving

Understand the problem

Carefully read the problem statement and, think about the desired output. The output should be the two variables with their values swapped. For instance, if n1 contains 10 and n2 contains 20, after swapping the values n1 should contain 20 and n2 should contain 10.

Come up with a practical solution

Pick two numbers. Suppose n1 contains 1, and n2 contains 4. Think of ways to swap the values. For example, we can save the value in n1 someplace else, store the value of n2 in n1, get the old value of n1, and store the old value of n1 in n2.

Click on the boxes below to change the value of the two numbers n1 and n2 (you can enter values between -10000 and 10000, both inclusive) and hit the Done button to see how it works:

Get hands-on with 1200+ tech skills courses.