Swap Two Numbers in C++

Swap two numbers in C++ using a temporary variable.

BeginnerBasic ProgramsExample 5 of 14
swap-two-numbers.cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int a, b, temp;
6
7 cout << "Enter first number (a): ";
8 cin >> a;
9
10 cout << "Enter second number (b): ";
11 cin >> b;
12
13 cout << "Before swapping: a = " << a << ", b = " << b << endl;
14
15 // Swapping logic
16 temp = a;
17 a = b;
18 b = temp;
19
20 cout << "After swapping: a = " << a << ", b = " << b << endl;
21
22 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.