Write a C++ Program to Swap Two Numbers

In C++, swapping two numbers is a straightforward process.

To swap two variables, we need to create a temporary variable to hold one of the variables’ values.

Then, we can assign the first variable’s value to the second variable and the temporary variable’s value to the first variable.

Here’s a simple program that demonstrates how to swap two numbers in C++:

#include <iostream>
using namespace std;

int main() {
    int num1 = 5, num2 = 10, temp;
    cout << "Before swapping: num1 = " << num1 << ", num2 = " << num2 << endl;

    // Swapping num1 and num2
    temp = num1;
    num1 = num2;
    num2 = temp;

    cout << "After swapping: num1 = " << num1 << ", num2 = " << num2 << endl;

    return 0;
}

In the above program, we first declare two integer variables num1 and num2 with initial values of 5 and 10, respectively.

Then, we declare a third variable temp to store the value of num1.

We print the values of num1 and num2 before swapping them using the cout statement.

To swap the values of num1 and num2, we first assign the value of num1 to temp. Then, we assign the value of num2 to num1.

Finally, we assign the value of temp to num2. After the swap, we print the new values of num1 and num2.

This program outputs the following:

Before swapping: num1 = 5, num2 = 10
After swapping: num1 = 10, num2 = 5

That’s it! With just a few lines of code, we can easily swap two numbers in C++.