C++ Program to Swap Two Numbers
In this example, we will Find Size of int, float, double and char in Your System using C++ cout statement.
Program to Add Two Numbers
This example contains two different techniques to swap numbers in C programming. The first program uses temporary variable to swap numbers, whereas the second program doesn't use temporary variables.
Example 1: Program to Swap Two Numbers (Using Temporary Variable)
#include <iostream>
using namespace std;
int main()
{
int a = 2, b = 4, temp;
cout << "Before swapping." << endl;
cout << "a = " << a << ", b = " << b << endl;
temp = a;
a = b;
b = temp;
cout << "\nAfter swapping." << endl;
cout << "a = " << a << ", b = " << b << endl;
return 0;
}
Output
Before swapping. a = 2, b = 4 After swapping. a = 4, b = 2
Working of above Program
In this program, three variables are used.
The contents of the first variable is copied into the temp variable. Then, the contents of second variable is copied to the first variable.
Finally, the contents of the temp variable is copied back to the second variable which completes the swapping process.
You can also perform swapping using only two variables as below.
Example 2: Program to Swap Two Numbers (Without Using Temporary Variable)
#include <iostream>
using namespace std;
int main()
{
int a = 2, b = 4;
cout << "Before swapping." << endl;
cout << "a = " << a << ", b = " << b << endl;
a = a + b;
b = a - b;
a = a - b;
cout << "\nAfter swapping." << endl;
cout << "a = " << a << ", b = " << b << endl;
return 0;
}
Output
The output of this program is the same as the first program above.
Before swapping. a = 2, b = 4 After swapping. a = 4, b = 2
Working of above Program
Let us see how this program works:
- Initially,
a = 2
andb = 4
. - Then, we add a and b and store it in a with the code
a = a + b
. This meansa = 2 + 4
. So,a = 6
now. - Then we use the code
b = a - b
. This meansb = 6 - 2
. So,b = 4
now. - Again, we use the code
a = a - b
. This meansa = 6 - 4
. So finally,a = 2
.
Hence, the numbers have been swapped.
Note: We can use multiplication and division instead of addition and subtraction. However, this won't work if one of the numbers is 0.
int a = 2, b = 4;
// using multiplication and division for swapping
a = a * b; // a = 8
b = a / b; // b = 2
a = a / b; // a = 4
Next Example
We hope that this Example helped you develop better understanding of the concept of Swapping Two Numbers in C++.
Keep Learning : )
In the next Example, we will learn about C++ Find ASCII Value of a Character
.