Challenge #6 :
- Switch the values of two variables without using a third variable.
I did pm my code to you since there is practically only one useable way to do this.
The only way I know to do this is to use he Xor operator:
'Uses Xor to switch variables 'Richard Clark 'FreeBasic 'Public Domain dim as integer a = 100, b = 456 print "A =";a, "B = ";b 'Use Xor to switch a = a xor b b = b xor a a = a xor b print "A =";a, "B = ";b sleep
Rick, you can do it with simple math ;)
a = 1
b = 2
a = a + b (makes, a = 3 and b = 2)
b = a - b (makes, a = 3 and b = 1)
a = a - b (makes, a = 2 and b = 1)
Heh. I didn't think of that. Cool.
I think this works with any "complementary" functions, i.e. where you have one function that removes the effect of the other, e.g. +/-, xor/xor and i haven't tried, but i'm thinking functions like exp/log as well. So here's my contribution:
a = 5
b = 10
a = a * b (a = 50, b = 10)
b = a / b (a = 50, b = 5)
a = a / b (a = 10, b = 5)
These methods only work in theory because of limited space. I think only rickclark's method is a safe solution.
console.initialize dim tmp dim a dim b a = " Hello " b = " World " console.writeline(a & b) tmp = b b = a a = tmp console.writeline(a & b) console.readline console.terminate
Unfortenately you did misunderstund this challeng. Idea is to change values of two variable with out using third variable wich in your case is tmp.
Oh didn't see that part.