This article guide you for writing a Program in C++ which swap the two numbers. Here, We had discussed two methods to swap the two numbers in C++ :
- Using Third Variable
- Without Using Third Variable
Matrix Multiplication Program in C++.
Using Third Variable
Let’s see a simple C++ example to swap two numbers using third variable.
#include <iostream> using namespace std; int main() { int a = 4, b = 6, 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 = 4, b = 6 After swapping. a = 6, b = 4
Without Using Third Variable
We can swap two numbers without using third variable. There are two common ways to swap two numbers without using third variable:
- By product and divide
- By addition and subtraction
Program 1: Using product and divide
Let’s see a simple C++ example to swap two numbers without using third variable.
#include <iostream> using namespace std; int main() { int a=4, b=6; cout<<"Before swap a= "<<a<<", b= "<<b<<endl; a=a*b; //a=24 (4*24) b=a/b; //b=4 (24/6) a=a/b; //a=6 (24/4) cout<<"After swap a= "<<a<<", b= "<<b<<endl; return 0; }
Output:
Before swap a= 4, b= 6 After swap a= 6, b= 4
Program 2: Using addition and subtraction
Let’s see another example to swap two numbers using addition( + ) and subtraction( – ).
#include <iostream> using namespace std; int main() { int a=4, b=6; cout<<"Before swap a= "<<a<<", b= "<<b<<endl; a=a+b; //a=10 (4+6) b=a-b; //b=4 (10-6) a=a-b; //a=6 (10-4) cout<<"After swap a= "<<a<<", b= "<<b<<endl; return 0; }
Output:
Before swap a= 4, b= 6
After swap a= 6, b= 4
Note: If you interested lo learn C++ through web, You can click here
Conclusion:
Hi guys, I can hope that you can know that how to write a Program in C++ which swap the two numbers. If you like this post as well as know something new so share this article in your social media accounts. If you have any doubt related to this post then you ask in comment section.