In this program, I will explain how to swap two numbers using c++ program with the help of temporary variable. in this program, we are using the three variables a, b and temp.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include <iostream> using namespace std; int main() { int a = 5, b = 10, temp; cout << "Before swapping the number." << endl; cout << "a = " << a << ", b = " << b << endl; temp = a; a = b; b = temp; cout << "****************" << endl; cout << "\nAfter swapping the number." << endl; cout << "a = " << a << ", b = " << b << endl; return 0; } |
Before swapping.
a = 5, b = 10
****************
After swapping.
a = 10, b = 5
Below is the anothe example of number swapping without using any third variable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include <iostream> using namespace std; int main() { int a = 5, b = 10; cout << "Before swapping the number." << endl; cout << "a = " << a << ", b = " << b << endl; a = a + b; b = a - b; a = a - b; cout << "****************" << endl; cout << "\nAfter swapping the number." << endl; cout << "a = " << a << ", b = " << b << endl; return 0; } |
Before swapping.
a = 5, b = 10
****************
After swapping.
a = 10, b = 5
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: C++ Tutorial, program to swap two numbers in c, swap two numbers in c, Swap Two Numbers using C++ Program