Question:
Make a program in C++ which swaps the value of two variables without using a third variable.?
Rishav Guha
2013-07-03 09:05:12 UTC
The value of the variables initially may be user-defined or programmer defined. Just make a program that can swap the values without using a third variable.
Four answers:
_Object
2013-07-03 09:22:15 UTC
Lol?

std::swap(a, b);



@Brian:

How can be so rude, and than not even answer the question? That's not acceptable.



But really though.

a = a + b

b = a - b

a = a - b

I'll confess, it took some thought.

Or you can use an XOR swap algorithm which will work for any object, even those without nifty inverse operations; the operation takes place bitwise on the same pattern as the addition solution above. The algorithm is not mine.



Edit:

To use this as intended with any type, you need to reinterpret_cast the complex object into an integral type and than apply the algorithm.



template

void Switch (Ty * x, Ty * y) {

if (x == y)

return;

*x ^= *y;

*y ^= *x;

*x ^= *y;



}
Prashant
2013-07-03 16:07:05 UTC
C++ Program to swap two values without using third variable

http://programming-examples.com/2013/04/c-program-to-swap-two-values-without-using-third-variable/
?
2016-11-09 15:15:08 UTC
particularly, there is an engineering application of types...a pair particularly. For smart canines with mischievous approaches, agility activities could be an marvelous thank you to channel all that love of tunnels and angles, hurdles and rapid turns...(they have instructions with little hurdles--pug-sized, you already know) in the journey that your canines has already had undertaking-loose sit down-stay-down coaching, you may strengthen him to provider canines status. i think of of that they had desire to have the canines solid Citizen certificates, and then one extra advantageous coaching for party or strengthen non-skittishness around wheel chairs, carts, that variety of element. i understand Cedars has a provider canines application, and sorting out on your schedule (pondering which you're able to could desire to rigidity him there), you have your canines pass to victims who're in restoration from surgical therapy, or those on longterm medical employer stay, as with out postpone as each and each week or as with out postpone as a month...you does now no longer have self belief the version a canines with interminable cuteness or mischievous approaches could make interior the life of a guy or woman constrained to a medical employer mattress.
anonymous
2013-07-03 09:09:12 UTC
use addition


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Continue reading on narkive:
Loading...