Home » Blog » Swap Two Numbers

Swap Two Numbers

Swap means exchange the value of two variable.

There is four different method.

  1. Using Temporary Variable
  2. Without Using Temporary Variable
  3. Using Bitwise Operator
  4. Using Multiplication And Division

Using Temporary Variable

#include <iostream>
using namespace std;

int main()
{
    int a = 31, b = 12, temp;

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

    temp = a;
    a = b;
    b = temp;

    cout << "\nAfter swapping" << endl;
    cout << "a = " << a << ", b = " << b << endl;

    return 0;
}

OutPut

Before swapping
a = 31, b = 12

After swapping
a = 12, b = 31

Without Using Temporary Variable

#include <iostream>
using namespace std;

int main()
{
    
    int a = 31, b = 12;

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

    a = a + b;
    b = a - b;
    a = a - b;

    cout << "\nAfter swapping" << endl;
    cout << "a = " << a << ", b = " << b << endl;

    return 0;
}

OutPut

Before swapping
a = 31, b = 12

After swapping
a = 12, b = 31

Using Bitwise Operator

#include <iostream>
using namespace std;

int main()
{
    int a = 31, b = 12, temp;
	
    cout << "Before swapping." << endl;
    cout << "a = " << a << ", b = " << b << endl;

    a = a^b;
    b = a^b;
    a = a^b;

    cout << "\nAfter swapping." << endl;
    cout << "a = " << a << ", b = " << b << endl;
	
    return 0;
}

OutPut

Before swapping
a = 31, b = 12

After swapping
a = 12, b = 31

Using Multiplication And Division

#include <iostream>
using namespace std;

int main()
{
    int a = 31, b = 12, temp;
	
    cout << "Before swapping." << endl;
    cout << "a = " << a << ", b = " << b << endl;

    a = a*b;
    b = a/b;
    a = a/b;

    cout << "\nAfter swapping." << endl;
    cout << "a = " << a << ", b = " << b << endl;
	
    return 0;
}

OutPut

Before swapping
a = 31, b = 12

After swapping
a = 12, b = 31

Leave a Reply

Your email address will not be published.