here is a really simple program to swap 2 numbers without using a third variable.
say you have 2 numbers a and b;
now what you do is add a in b.
then save b-a in a.now save b-a in b.
{
int a=3,b=2;
cout<<"Initially to "<<a<<" "<<b;
{
b+=a;
a=b-a;
b=b-a;
}
cout<<"Swapped to "<<a<<" "<<b;
}
take care of the sequence.b takes a+b. now we put b in a by a=(b-a);meaning a=b(initial value).so now a=b-initial.so b=b-a..
simple.
swapping
Started by Chinmoy, Mar 02 2008 01:39 AM
7 replies to this topic
#1
Posted 02 March 2008 - 01:39 AM
|
|
|
#2
Posted 02 March 2008 - 01:41 AM
try to do this with pointers..
#3
Posted 07 March 2008 - 08:19 PM
#4
Posted 15 March 2008 - 11:50 AM
This is not so much of thinking outside the box as it is thinking like we're in the 70's. This is an unoptimization that exhibits undefined behavior.
#5
Posted 15 March 2008 - 12:40 PM
dcs said:
This is not so much of thinking outside the box as it is thinking like we're in the 70's. This is an unoptimization that exhibits undefined behavior.
Is it?
What behavior is undefined?
What would you say is a smarter way to do it?
________________________________________________
"I'm not young enough to know everything." - Oscar Wilde
"I'm not young enough to know everything." - Oscar Wilde
#6
Posted 15 March 2008 - 12:57 PM
Walle said:
Is it?
What behavior is undefined?
What behavior is undefined?
Walle said:
What would you say is a smarter way to do it?
#7
Posted 15 March 2008 - 01:39 PM
Ah, I get it.
How about unsigned behaviour on overflow? Always wrap or is it also undefined?
How about unsigned behaviour on overflow? Always wrap or is it also undefined?
________________________________________________
"I'm not young enough to know everything." - Oscar Wilde
"I'm not young enough to know everything." - Oscar Wilde
#8
Posted 15 March 2008 - 03:12 PM
Unsigned integer overflow is well-defined as wrapping.


Sign In
Create Account


Back to top









