how to write c++swap the content of 2 variables using athird variable

1 answer

To swap the content of two variables using a third variable in C++, you can follow the below steps:

1. Declare three variables, two for the values to be swapped and one for storing temporary value.
2. Assign values to the variables that you want to swap.
3. Print both the variables before swapping to verify their values.
4. Use the third variable to swap the values as follows:

temp = variable1;
variable1 = variable2;
variable2 = temp;

5. Print both the variables after swapping to verify their values.

Here is an example code:

```
#include<iostream>
using namespace std;

int main() {

int variable1 = 10, variable2 = 20, temp;

cout << "Before swapping:" << endl;
cout << "Variable 1 = " << variable1 << ", Variable 2 = " << variable2 << endl;

temp = variable1;
variable1 = variable2;
variable2 = temp;

cout << "\nAfter swapping:" << endl;
cout << "Variable 1 = " << variable1 << ", Variable 2 = " << variable2 << endl;

return 0;
}
```

Output:

```
Before swapping:
Variable 1 = 10, Variable 2 = 20

After swapping:
Variable 1 = 20, Variable 2 = 10
```

In the above code, we declared three variables: `variable1`, `variable2`, and `temp`. We assigned values 10 and 20 to `variable1` and `variable2` respectively. Then we printed both variables before swapping their values. After that, we used the third variable `temp` to swap the values of `variable1` and `variable2`. Finally, we printed both variables after swapping their values to verify that they have been swapped successfully.