Swap two Values with third Variable
#include <iostream>
using namespace std;
int main () {
int x, y, temp;
cout << "Enter a value for x: ";
cin >> x;
cout << "Enter a value for y: ";
cin >> y;
cout << "Before swapping:\nX: " << x << "\nY: " << y << endl;
// swapping numbers
temp = x;
x = y;
y = temp;
cout << "After swapping:\nX: " << x << "\nY: " << y;
return 0;
}
Output
Enter a value for x: 22
Enter a value for y: 44
Before swapping:
X: 22
Y: 44
After swapping:
X: 44
Y: 22
Swap two Values without third Variable
#include <iostream>
using namespace std;
int main () {
int x, y;
cout << "Enter a value for x: ";
cin >> x;
cout << "Enter a value for y: ";
cin >> y;
cout << "Before swapping:\nX: " << x << "\nY: " << y << endl;
// swapping numbers
x = x + y;
y = x - y;
x = x - y;
cout << "After swapping:\nX: " << x << "\nY: " << y;
return 0;
}
Output
Enter a value for x: 22
Enter a value for y: 44
Before swapping:
X: 22
Y: 44
After swapping:
X: 44
Y: 22