C++ - Swap two numbers without using Temporary Variable


Advertisements

The value of two variables can be swapped without using any temporary variables. The method involves using operators like +, *, / and bitwise.

Example: Using + operator

In the below example, the + operator is used to swap the value of two variables x and y.

#include <iostream>
using namespace std;

static void swap(int, int);

static void swap(int x, int y) {
    cout<<"Before Swap.\n";
    cout<<"x = "<<x<<"\n";
    cout<<"y = "<<y<<"\n";

    //Swap technique
    x = x + y;
    y = x - y;
    x = x - y;

    cout<<"After Swap.\n";
    cout<<"x = "<<x<<"\n";
    cout<<"y = "<<y<<"\n";
}

int main() {
  swap(10, 25);
  return 0;
}

Output

Before Swap.
x = 10
y = 25
After Swap.
x = 25
y = 10

Example: Using * operator

Like + operator, the * operator can also be used to swap the value of two variables x and y.

#include <iostream>
using namespace std;

static void swap(int, int);

static void swap(int x, int y) {
    cout<<"Before Swap.\n";
    cout<<"x = "<<x<<"\n";
    cout<<"y = "<<y<<"\n";

    //Swap technique
    x = x * y;
    y = x / y;
    x = x / y;

    cout<<"After Swap.\n";
    cout<<"x = "<<x<<"\n";
    cout<<"y = "<<y<<"\n";
}

int main() {
  swap(10, 25);
  return 0;
}

Output

Before Swap.
x = 10
y = 25
After Swap.
x = 25
y = 10

Example: Using / operator

Smilarly / operator can also be used to swap the value of two variables x and y.

#include <iostream>
using namespace std;

static void swap(float, float);

static void swap(float x, float y) {
    cout<<"Before Swap.\n";
    cout<<"x = "<<x<<"\n";
    cout<<"y = "<<y<<"\n";

    //Swap technique
    x = x / y;
    y = x * y;
    x = y / x;

    cout<<"After Swap.\n";
    cout<<"x = "<<x<<"\n";
    cout<<"y = "<<y<<"\n";
}

int main() {
  swap(10, 25);
  return 0;
}

Output

Before Swap.
x = 10
y = 25
After Swap.
x = 25
y = 10

Example: Using bitwise operator

The bitwise XOR (^) operator can also be used to swap the value of two variables x and y. It returns 1 when one of two bits at same position in both operands is 1, otherwise returns 0.

#include <iostream>
using namespace std;

static void swap(int, int);

static void swap(int x, int y) {
    cout<<"Before Swap.\n";
    cout<<"x = "<<x<<"\n";
    cout<<"y = "<<y<<"\n";

    //Swap technique
    x = x ^ y;
    y = x ^ y;
    x = x ^ y;

    cout<<"After Swap.\n";
    cout<<"x = "<<x<<"\n";
    cout<<"y = "<<y<<"\n";
}

int main() {
  swap(10, 25);
  return 0;
}

Output

Before Swap.
x = 10
y = 25
After Swap.
x = 25
y = 10

Disadvantages of using above methods

  • The multiplication and division based approaches fail if the value of one of the variable is 0.
  • The addition based approach may fail due to arithmetic overflow. If x and y are too large, operation performed on operands may result into out of range integer.


Recommended Pages


Advertisements