Write a C++ program that swaps the values of two numbers provided by the user.
Input and Output Examples
- 
Input: a = 5, b = 10 Output: a = 10, b = 5 
- 
Input: a = -3, b = 7 Output: a = 7, b = -3 
Algorithm to swap two numbers:
- Start the Program: Include necessary headers and use the standard namespace.
- Prompt for Input: Ask the user to enter two numbers.
- Read the Input: Store the input numbers in variables a and b.
- Swap the Numbers: Utilize a method to swap the values of a and b.
- Display the Output: Print the swapped values.
- End the Program: Finish execution.
C++ Program with Different Methods to Swap Numbers
Below are three common methods to swap two numbers in C++:
 
Method 1: C++ program to swap two numbers using a Temporary Variable
This is the most straightforward approach, using an extra variable to temporarily hold one of the values during the swap.
#include <iostream> 
using namespace std; 
int main() {
    // Declare the variables for the numbers and a temporary variable.
    int a, b, temp; 
    // Take input values
    cout << "Enter two numbers:\n"; 
    cin >> a >> b; 
    
    // Swapping using a temporary variable
    temp = a; // Store the value of a in temp.
    a = b; // Transfer the value of b to a.
    b = temp; // Transfer the value stored in temp to b.
    cout << "After swapping:\n" << "a = " << a << ", b = " << b << endl; // Display the swapped values.
    return 0; // End the program successfully.
}
Method 2: Without Using a Temporary Variable (Arithmetic Operations)
This method uses arithmetic operations to swap values without a temporary variable. However, it may lead to overflow for very large integers.
#include <iostream>
using namespace std;
int main() {
    int a, b;
    cout << "Enter two numbers:\n";
    cin >> a >> b;
    // Swapping without a temporary variable using addition and subtraction
    a = a + b; // Sum of a and b stored in a
    b = a - b; // Original value of a (a+b) minus b gives the original a, now stored in b
    a = a - b; // Original value of a (a+b) minus new b (original a) gives original b
    cout << "After swapping:\n" << "a = " << a << ", b = " << b << endl;
    return 0;
}
Method 3: Using Bitwise XOR Operator
The XOR swap is a neat trick for integers that uses bitwise XOR to swap values without a temporary variable.
#include <iostream>
using namespace std;
int main() {
    int a, b;
    cout << "Enter two numbers:\n";
    cin >> a >> b;
    // Swapping using bitwise XOR
    a ^= b; // Step 1: a becomes a XOR b
    b ^= a; // Step 2: b becomes b XOR (a XOR b) which is a
    a ^= b; // Step 3: a becomes (a XOR b) XOR a which is b
    cout << "After swapping:\n" << "a = " << a << ", b = " << b << endl;
    return 0;
}