Search⌘ K
AI Features

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

C++
#include <iostream>
using namespace std;
int main() {
// Initialize variables var1, var2 and temp
int var1 = 10;
int var2 = 20;
int temp;
// Print the values of var1 and var2
cout << "Initial values of var1 and var2 are:" << endl;
cout << "var1 = " << var1 << endl;
cout << "var2 = " << var2 << endl;
// Stores value of var1 in temp
temp = var1;
// Stores value of var2 in var1
var1 = var2;
// Stores value of temp in var2
var2 = temp;
cout << "After swapping:" << endl;
cout << "var1 = " << var1 << endl;
cout << "var2 = " << var2;
}

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.