C++ Program to Swap Two Numbers

C++ Program to Swap Two Numbers

When learning C++, one of the first small but powerful programs you’ll come across is swapping two numbers. At first, it may look like a very simple problem, but it teaches important ideas about variables, data handling, and logic. Swapping numbers is used in many real-world situations such as sorting algorithms, data manipulation, and even in games when values need to be exchanged. In this article, we will walk through different ways of writing a C++ program to swap two numbers, step by step, in a simple and beginner-friendly manner.

Program 1: Swapping Numbers Using a Temporary Variable

The most common and easiest method to swap two numbers in C++ is by using a temporary variable. This method is beginner-friendly because it is easy to understand and follow.

#include <iostream>

using namespace std;

int main() {

    int a, b, temp;  // declare three integers: a, b, and a temporary variable temp

    cout << "Enter two numbers: " << endl; // ask the user for two numbers
    cin >> a >> b;   // read input values into a and b

    cout << "Before swapping: a = " << a << ", b = " << b << endl;

    temp = a;  // store the value of a in temp
    a = b;     // assign the value of b to a
    b = temp;  // assign the stored value (original a) from temp to b

    cout << "After swapping: a = " << a << ", b = " << b << endl; // print swapped values

    return 0;  // end the program

}

In this program, we ask the user to enter two numbers. The value of a is stored in temp, then the value of b is assigned to a, and finally the value stored in temp is assigned to b. This way the values of a and b are swapped. It is useful for beginners because it shows how a third variable can hold data temporarily and help in exchanging values safely.

Program 2: Swapping Numbers Using Arithmetic Operations

Sometimes, you may not want to use an extra variable. In that case, you can swap numbers using arithmetic operations. This method is clever because it avoids using extra space.

#include <iostream>

using namespace std;

int main() {

    int a, b;  // declare two integers: a and b

    cout << "Enter two numbers: " << endl; // ask the user for two numbers
    cin >> a >> b;   // read input values into a and b

    cout << "Before swapping: a = " << a << ", b = " << b << endl;

    a = a + b;  // step 1: add a and b, store the sum in a
    b = a - b;  // step 2: subtract b from the sum, result is the original value of a
    a = a - b;  // step 3: subtract the new b (old a) from the sum, result is the original value of b

    cout << "After swapping: a = " << a << ", b = " << b << endl; // print swapped values

    return 0;  // end the program

}

Here, we first add the two numbers and store the result in a. Then we subtract b from this sum to get the original value of a, and assign it to b. Finally, we subtract the new value of b from the sum to get the original value of b and assign it to a. This approach helps learners understand how mathematical operations can be used creatively in programming. However, it is not always safe for very large numbers because it may cause overflow.

Program 3: Swapping Numbers Using XOR Operator

Another interesting way to swap two numbers is by using the XOR bitwise operator. This method avoids temporary variables and does not use addition or subtraction.

#include <iostream>

using namespace std;

int main() {

    int a, b;  // declare two integers: a and b

    cout << "Enter two numbers: " << endl; // ask the user for two numbers
    cin >> a >> b;   // read input values into a and b

    cout << "Before swapping: a = " << a << ", b = " << b << endl;

    a = a ^ b;  // step 1: a becomes a XOR b
    b = a ^ b;  // step 2: b becomes (a XOR b) XOR b, which is the original a
    a = a ^ b;  // step 3: a becomes (a XOR b) XOR a, which is the original b

    cout << "After swapping: a = " << a << ", b = " << b << endl;

    return 0;

}

In this program, the XOR operator is used three times to swap the values of a and b. Each step cleverly changes the values without needing extra memory or arithmetic operations. This is a popular method in computer science for its efficiency, though it can look confusing for beginners at first. With practice, you will see how logical operations like XOR can solve problems in unique ways.

Program 4: Swapping Numbers Using a Function

Sometimes, instead of writing the swapping logic directly in the main() function, it is better to create a separate function. This makes the code reusable and clean, especially when you need to swap numbers in multiple places.

#include <iostream>

using namespace std;

// Function to swap two numbers using references
void swapNumbers(int &x, int &y) {

    int temp = x; // store x in temp
    x = y;        // assign y to x
    y = temp;     // assign temp (old x) to y

}

int main() {

    int a, b;
    cout << "Enter two numbers: " << endl;
    cin >> a >> b;

    cout << "Before swapping: a = " << a << ", b = " << b << endl;

    // Call the function to swap
    swapNumbers(a, b);

    cout << "After swapping: a = " << a << ", b = " << b << endl;

    return 0;

}

Here, we created a function called swapNumbers that takes two numbers by reference. The function then swaps them using a temporary variable. By passing the variables by reference, any changes inside the function directly affect the original variables. This method is useful in larger projects because it makes the swapping logic modular and easy to reuse. Beginners will also see how functions can simplify code structure.

Program 5: Swapping Predefined Variables

In some cases, you may not want the user to enter numbers at all. Instead, you can define the values directly inside the program and swap them. This approach is quick and helpful for testing or when working with fixed data.

#include <iostream>

using namespace std;

int main() {

    int a {10}, b {20}; // predefined values {a: 10, b: 20}

    cout << "Before swapping: a = " << a << ", b = " << b << endl;

    // swapping with temporary variable
    int temp = a;
    a = b;
    b = temp;

    cout << "After swapping: a = " << a << ", b = " << b << endl;

    return 0;

}

In this program, we assigned 10 to a and 20 to b. We then swapped them using a temporary variable, just like in Program 1. This style is useful when you already know the values beforehand or when writing small test cases. For beginners, it’s a simple way to focus only on the swapping logic without worrying about user input.

Program 6: Swapping Numbers Using Initializer List

C++11 introduced initializer lists, and we can use them to swap numbers in a very short and elegant way. It looks a bit modern, but it’s fun and worth knowing.

#include <iostream>

using namespace std;

int main() {

    int a {10}, b {20}; // predefined values {a: 10, b: 20} 

    cout << "Before swapping: a = " << a << ", b = " << b << endl;

    // swap using initializer list
    a = (initializer_list<int>{b, b = a}).begin()[0];

    cout << "After swapping: a = " << a << ", b = " << b << endl;

    return 0;

}

In this code, we used an initializer_list to perform the swap in a single line. What happens here is that the list temporarily stores values, assigns a to b, and then gives a the stored value of b. While this may look tricky for beginners, it shows how powerful and creative C++ can be. It’s not the most common method, but it’s a clever trick for advanced learners who want to see different approaches to the same problem.

Frequently Asked Questions (FAQ)

Swapping numbers in C++ often raises small questions for beginners. Let’s clear up some common doubts.

Q1: Why do we need to learn swapping numbers?
Swapping numbers is a building block for bigger problems. It is often used in algorithms such as sorting, where data needs to be rearranged.

Q2: Which method is the best to use?
For beginners, using a temporary variable is the simplest and safest. The arithmetic and XOR methods are useful to learn once you are comfortable with the basics.

Q3: Can swapping be done with functions?
Yes, you can create a function in C++ that swaps numbers. This is helpful when you need to reuse the swapping logic many times in larger programs.

Conclusion

Swapping two numbers in C++ may seem simple, but it opens the door to understanding key programming concepts like variables, operators, and memory usage. We explored three main methods: using a temporary variable, using arithmetic operations, and using the XOR operator. Each has its own advantages, and practicing them will help you grow more confident in C++. Keep experimenting, try adding functions, and slowly apply these techniques in bigger projects.

Additional & References

If you want to explore further and strengthen your C++ skills, it’s good to study more about variables, operators, and functions. With practice, you’ll see how a small concept like swapping can become a foundation for solving larger problems.

Scroll to Top