Swap Two Numbers in C++
Swap two numbers in C++ using a temporary variable.
1#include <iostream>2using namespace std;34int main() {5 int a, b, temp;67 cout << "Enter first number (a): ";8 cin >> a;910 cout << "Enter second number (b): ";11 cin >> b;1213 cout << "Before swapping: a = " << a << ", b = " << b << endl;1415 // Swapping logic16 temp = a;17 a = b;18 b = temp;1920 cout << "After swapping: a = " << a << ", b = " << b << endl;2122 return 0;23}
Output
Enter first number (a): 5 Enter second number (b): 10 Before swapping: a = 5, b = 10 After swapping: a = 10, b = 5
What's going on
This C++ program swaps two integers using a temporary variable. After a correct swap, a and b have traded values.
int a, b, temp;
Three integers. a and b come from cin. temp is only a parking spot.
cin >> a; then cin >> b;
Sample: 5 and 10.
cout << "Before swapping: a = " << a << ", b = " << b << endl;
Print first. If you skip this, you can't tell whether the swap ran.
temp = a;
Park 5. Without this, the next assignment throws 5 away.
a = b;
a is 10. b is still 10. Stop here and both are 10.
b = temp;
b gets the parked 5. After: a = 10, b = 5. Matches the output.
std::swap(a, b) in <algorithm> does the same three assignments. XOR swap (a ^= b; b ^= a; a ^= b;) exists and breaks when a and b are the same location. Three lines with temp is the version to write on paper.
Swapping without temp using a = a + b; b = a - b; a = a - b; overflows for large ints. Don't.