Swap Two Numbers Without using Third Variable
Here you will learn a new method that can change the values of two variable without using third variable. We will implement this by C++ Program to Swap Two Numbers Without using Third Variable. Let’s understand this simple swapping method by example.
Example:-
x=5 and y=10
x = x + y;
y = x – y;
x = x – y;
C++ Program to Swap Two Numbers Without using Third Variable
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 x, y, temp; cout<<"\nEnter the value of x and y\n"; cin>>x>>y; cout<<"\nBefore Swapping\nx = "<<x<<"\ny = "<<y; // swapping x = x + y; y = x - y; x = x - y; cout<<"\nAfter Swapping\nx = "<<x<<"\ny = "<<y; return 0; } |
Output
Check out our other C++ programming Examples