C++ Program To Swap Two Numbers Without Using Third Variable Using Functions
In this tutorial, we need to write a Program for Swapping Two Numbers in C++ without using a third variable and by using functions.
We can swap two numbers without using a third variable. There are two common ways to swap two numbers without using a third variable:
- By + and -
- By * and /
Swap Two Numbers Without Using Third Variable Using Functions In C++
#include <iostream>
using namespace std;
int main()
{
cout << "\n\nWelcome to Studytonight :-)\n\n\n";
cout << " ===== Program to Swap two numbers without using a 3rd variable ===== \n\n";
// variable declaration
int a,b;
//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
// without using any extra variable
a = a + b;
b = a - b;
a = a - b;
cout << "\n\nValues After Swapping: \n"<<endl;
cout << "First Number = " << a <<endl;
cout << "Second Number = " << b <<endl;
cout << "\n\n\n";
return 0;
}
Welcome to Studytonight :-)
===== Program to Swap two numbers without using a 3rd variable =====
Enter the first number : 41
Enter the second number : 5
Values Before Swapping:
First Number = 41
Second Number = 5
Values After Swapping:
First Number = 5
Second Number = 41
Let's break down the parts of the code for better understanding.
//Logic for swapping the two numbers without using any extra variable
a = a + b;
b = a - b;
a = a - b;
The logic involved here is that, similar to every other programming language, the variables in C++ store the most recent value stored into it.
To understand the above logic, let's use some dummy values.
Initially, a = 30
, b=55
,
Then we do, a = a + b
, so new value stored in a is:
a = 30 + 55
Then, b = a - b
, here the a would be the most recently stored value.
So, b = (30 + 55) - 55 = 30
i.e. b = 30 (the initial value of a)
Finally we do, a = a - b
,
So, a = (30 + 55) - 30 = 55
i.e. a = 55 (the initial value of b)
So as you can see, we have swapped the initial values of a
and b
into each other.
Conclusion
Here, in this tutorial, we have learned how to use functions to swap two numbers given by the user.