LAST UPDATED: OCTOBER 12, 2020
C++ Swap Two Numbers using a 3rd Variable
Hello Everyone!
In this tutorial, we will learn how to Swap two numbers using a 3rd variable, in the C++ programming language.
Code:
#include <iostream>
using namespace std;
int main()
{
cout << "\n\nWelcome to Studytonight :-)\n\n\n";
cout << " ===== Program to Swap two numbers using a 3rd variable ===== \n\n";
//variable declaration
int a,b,temp;
//taking input from the command line (user)
cout << "Enter the first number : ";
cin >> a;
cout << "Enter the second number : ";
cin >> b;
cout<<"\n\nValues Before Swapping: \n"<<endl;
cout<<"First Number = " << a <<endl;
cout<<"Second Number = " << b <<endl;
//Logic for swapping the two numbers using an extra variable 'temp'
temp = a;
a = b;
b = temp;
cout << "\n\nValues After Swapping: \n"<<endl;
cout << "First Number = " << a <<endl;
cout << "Second Number = " << b <<endl;
cout << "\n\n\n";
return 0;
}
Output:
Now let's see what we have done in the above program.
Program Explained:
Let's break down the parts of the code for better understanding.
//Logic for swapping the two numbers using an extra variable 'temp'
temp = a;
a = b;
b = temp;
The logic involved here is that, similar to every other programming language, the variables in C++ stores the most recent value stored into it.
So, first we are putting the value of a
in a new variable temp
so that once b
's value is assigned to a
, the original value of a
isn't lost.
Then we assign the original value of a
to b
, by making use of temp
.
Keep Learning : )