Practice Exercise: Using Variables
Learn about the integer variable, the assignment operator, and the memory allocation.
Swapping the values
Write a program in the code editor below that swaps the values of two variables.
Let’s say we have two variables num1, which has the value 34 stored, and num2, which has the value 12 stored. Now we need to swap the values of the two variables such that num1 stores 12 and num2 stores 34.
Before swapping:
num1: 34
num2: 12
After swapping:
num1: 12
num2: 34
Write your solution in the editor below:
Swapping the values (with logical error)
Let’s try and swap the values of the two variables.
As we can see from the output above, both variables now have the value 34. We cannot simply swap the values of variables this way. When we store the value of num1 in num2, we lose the value of num2. So, we need to find a way to save the value of num2 first so it’s not overwritten.
A logical error is a mistake in reasoning by the programmer, not a mistake in the programming language. More intuitive example in real life would be this English sentence, “He chewed a mountain.” is a correct sentence grammatically but logically an incorrect sentence. These errors cannot be caught by the compiler. Programmers spend most of their lives finding logical errors and correcting them. We’ll discuss these errors further in the upcoming lessons.
Try swapping the values without the above logical error.
Swapping the values (using a third variable)
Don’t look at the solution if you haven’t tried solving the above problem yourself first.
Let’s use a third temporary variable int temp; to store the value of num2 before storing the value of num1 in num2.
We store the value of num2 inside temp in line 17. In line 19, we store the value of num1 in num2. In line 21, we store the value of temp in num1.
Swapping the values (without a third variable)
Now, can you swap the values even without using a third variable? Write a program in the code editor below that swaps the values of two variables without using any third variable.