C++ Program to Swap Two Numbers with and without using third variable

0

In this article, we will use two methods to swap two variables, one with a third variable and another without 3 third variable.

1. Program using the third variable

For using the third variable we will take two input as a and b and third variable temp. for the logic, we will first assign first variables in temp as temp = a,   and then we assign the value of b variable to a and then we will assign temp value to b. Here is the example –

a = 5,   b = 10

temp = a  //here temp = 5

a = b // Now value of a = 10

b = temp //and now as temp is 5 so b = 5

#include <iostream>
using namespace std;

int main()
{
    int a = 5, b = 10, 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 = 5, b = 10

After swapping.
a = 10, b = 5

2. Alternate Program using the third variable

For using third variable we will take two input as a and b and third variable temp. for the logic we will first add the variables in temp as temp = a+b, and then we will subtract the values one by one from temp and store them in another variable. Here is the example –

a = 5, b = 10

temp = a+b //here temp = 10+5 = 15

a = temp – a // Now value of a = 15-10  = 5

b = temp – b //and now value of b = 15 – 5 = 10

#include <iostream>
using namespace std;

int main()
{
    int a = 5, b = 10, 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 = 5, b = 10

After swapping.
a = 10, b = 5

3. Program without using the third variable

In this program, we will use a similar approach as we did in the 2nd program, just without using temp variable.  Now we will add the values to a and then subtract them. Here is the example to understand –

a = 5, b = 10

a = a + b //here a = 5 + 10 = 15

b =  a – b // Now since value of a is 15,  b = 15-10  = 5

a = a – b //Now since value of b is 5 , a =  15-5  = 10

#include <iostream>
using namespace std;

int main()
{
    int a = 5, b = 10;

    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 = 5, b = 10

After swapping.
a = 10, b = 5

Leave a Reply

Your email address will not be published. Required fields are marked *