This question came up on the forum. How do you swap two numbers without using a temporary variable? I used all the power of my brain to solve this at four o'clock in the morning. In all fairness, swapping two numbers using a temporay variable is about five times faster. This code is just for the curious.
Swapping two numbers
// swap two numbers without using a temporary variable
// the numbers can be either integers or floats
#include <iostream>
using namespace std;
int main()
{
float a = 1.7;
float b = -7.1;
cout << "a = " << a << " b = " << b << endl;
// swap a with b
a = a + b;
b = a - b;
a = a - b;
cout << "after swapping a with b:" << endl;
cout << "a = " << a << " b = " << b << endl;
cin.get(); // wait
return EXIT_SUCCESS;
}
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.