Swap Three Integers Without Temporary Variable in C++

It’s quite amusing to see how different variations of solutions for the same questions are thereby different individuals. From pretty ancient times maths has played a very vital role in civilizations. Not to mention how everything around us revolves mathematically. Now programming is more or less similar to that. It’s the second version of maths where to solve real-world problems you need to apply real-world mathematical concepts. However, as we’re talking about maths, how about writing a program to swap Integers. So today let’s write a simple program to Swap Three Integers Without Temporary Variable in C++.

What’s The Approach?

  • Let us consider a, b & c to be the numbers we want to swap with each other. Now the catch is to do this without using a temporary variable.
  • Firstly we’ll store the addition of these three variables in, one of the variables. That is, a = a + b + c
  • Now, we will subtract the value of a from b+c and assign this new value to b. i.e, b = a - (b+c)this way we’ll store the value of variable a into variable b.
  • Again we will subtract the value of a from b+c and assign this new value to c . i.e, c = a - (b+c) this way we’ll store the value of variable b into variable c.
  • For this final time, again we will subtract the value of a from b+c and assign this new value to a . i.e,  a = a - (b+c) this way we’ll store the value of variable c into variable a.
  • After the above three instructions finish executing we’ll print the values of a, b & c.

Also Read: Print Prime Numbers Between Two Integers in C++

C++ Program To Swap Three Integers Without Temporary Variable

 

Input:

a = 10, b = 20, c = 30

Output:

a = 30, b = 10, c = 20

// C++ program to swap three variables
// without using temporary variable.
#include <iostream>
using namespace std;

// Assign c's value to a, a's value to b and
// b's value to c.
void swapThree(int &a, int &b, int &c)
{
    // Store sum of all in a
    a = a + b + c; 

    // After this, b has value of a
    b = a - (b+c); 

    // After this, c has value of b
    c = a - (b+c); 

    // After this, a has value of c
    a = a - (b+c); 
}

// Driver code
int main()
{
    int a = 10, b = 20, c = 30;

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

    swapThree(a, b, c);

    cout << "After swapping a = " << a << ", b = "
        << b << ", c = " << c << endl;

    return 0;
}

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

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