i want to swap two numbers without using a third variable && an arithmetic operator
i want to swap two numbers without using a third variable && an arithmetic operator
Do you mean
A=B; and B=A; without using C?
I don't know that that can be done. I'm fairly certain than any library that would swap two numbers for you would just be doing the third variable and assignment operator under the surface.
What is that you're trying to accomplish by eliminating the third variable? Just less memory usage? In the context of a real program, the third variable is very insignificant.
Yes, there is an algorithm. If I remember it went like this:
a = 5;
b = 2;
// now 5,2
a -= b
// now 3,2
b += a
// now 3,5
a = b - a;
// now 2,5
But as I remember it didn't work with all numbers - ???
EDIT:
I'm sure it's his homework ...What is that you're trying to accomplish by eliminating the third variable? Just less memory usage? In the context of a real program, the third variable is very insignificant.
Last edited by kmdv; 08-25-2010 at 07:48 AM.
Why?
Pointless, but it works.Code:void swap(int *a, int *b) { *b += *a; *a = *b-*a; *b -= *a; }
That is, unless arithmetic overflow or underflow causes a trap on your machine.
The whole exercise is pointless. Tutors who think this kind of "spoon on your nose" magic trick is worth knowing should be avoided.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.