Swapping Variables in C++

Exercise:

Write a C++ code that can swap between two variables.

1. With Temporary Variable:

Click Here to View the Solution:
#include <iostream>
using namespace std;
int main()
{
    int x= 50,y= 100,temp;
    cout << "Before swapping " << endl;
    cout << "x = " << x << ", y = " << y << endl;
    temp = x;
    x = y;
    y = temp;
    cout << "\nAfter swapping " << endl;
    cout << "x = " << x << ", y = " << y << endl;
    return 0;
}
click here to view the output:
Before swapping.
 x = 50, y = 100
 After swapping.
 x = 100, y = 50
click here to view the explanation:
  • 3 variables have to be used for the above program. Variable x, y, and temp (temporary).
  • The contents of 1st variable are assigned to the temporary variable.
  • Then the contents of 2nd variable are put equal to the 1st variable.
  • The contents of temporary variable are now put equal to the second variable.
  • Now, the contents of 1st variable are equal to the contents of the 2nd variable and vice versa.
  • This code can be used for numbers and any other variables.

2. Without Temporary Variable:

Click Here To View The Solution:
#include <iostream>
using namespace std;
int main()
{
    int x = 50, y = 100;
    cout << "Before swapping." << endl;
    cout << "x = " << x << ", y = " << y << endl;
    x = x + y;
    y = x - y;
    x = x - y;
    cout << "\nAfter swapping." << endl;
    cout << "x = " << x << ", y = " << y << endl;
    return 0;
}
Click Here To View The Output:
Before swapping.
 x = 50, y = 100
 After swapping.
 x = 100, y = 50

Click Here To View The Explanation:

This code will give the exact same output as program 1. Let’s study the working of this code.  

We have assigned a number to 1st variable and 2nd variable; namely x and y, respectively.

  • x = 50, and y = 100
  • Now we give x a new value and put it equal to the sum of x and y.

Hence, x = x + y.

The new value of x = 50 + 100 = 150.

  • To switch values of x and y, we use simple algebraic equations.  
  • x is subtracted from the value assigned to y.

y = x – y

y = 150 – 100

y = 50.

  • Value of y is switched. For the next value of x to be switched, the new value of y is subtracted from the new value of x.

x =  x – y

x = 150 – 50

x = 100

  • This code is fixated to numbers.
  • Another code can be compiled to switch numbers without adding a temporary variable. Division and multiplication can be used to switch numbers.
  • For example, x = 10, y = 5
  • Starting with equations:

x = y * x                                  x = 5 * 10 = 50,

y = x / y                                   y = 50 / 5 = 10,

x = x / y                                   x = 50 / 10 = 5.

  • This new division and multiplication equations have a limitation. They can not be used for 0.