Software & Finance





C++ FAQ - How to swap the two numbers without using temporary variable?





It is easy to swap two numbers using a temporary variable.

    double a = 22.66;

    double b = 55.62;
double t = 0;

t = a;
a = b;
b = t;


How about  swaping the numbers with out using a temporary variable. Look at the sample code given below:


Source Code


 

#include <stdio.h>

#include <iostream>

#include <tchar.h>

 

 

int _tmain(int argc, _TCHAR* argv[])

{

    // Swap the two numbers with out using temporary variables

    double a = 22.66;

    double b = 55.62;

 

    std::cout << "Step1: " << a << "\t" << b << "\n";

    a = a + b; // Get the sum of two numbers and assign it to a

    std::cout << "Step2: " << a << "\t" << b << "\n";

    b = a - b; // a (sum) - b would give you original value of a and assign it to b.

    std::cout << "Step3: " << a << "\t" << b << "\n";

    a = a - b; // a (sum) - b(currently holds the orinial value of a) would give you b and assign it to a.

    std::cout << "Step4: " << a << "\t" << b << "\n";

 

    return 0;

}

Output


 

Step1: 22.66    55.62

Step2: 78.28    55.62

Step3: 78.28    22.66

Step4: 55.62    22.66