Solution Review: Swap the Values of Two Variables
Understand how to swap the values of two variables in C++ by using a temporary variable. This lesson breaks down each step of the process to show why the temp variable is essential to avoid losing data. You'll see how to exchange values correctly, reinforcing fundamental concepts in variables and constants for beginner programmers.
We'll cover the following...
Solution
Explanation
Let’s see what happens if we don’t use the temp variable.
Let’s step through the program above line by line:
Line No. 16: We store the value of var1 in temp for later use. The value of temp becomes 10. If we don’t store the value of var1 in temp, it is lost.
Line No. 18: Stores the value of var2 in var1. Now, the value of var1 is 20.
Line No. 20: Stores the value of temp in var2. Now, the value of var2 is 10.
🎉 Tada! We have just exchanged the values of variables. Programming is fun, right?
Let’s wrap up this chapter by completing a quiz in the upcoming lesson.