Perhaps a little late, but since it is not marked as solved I will give it a go. In order to swap two variables, denoted 'a' and 'b', using a third variable, denoted 'temp', you need to do the following:
1. place one of the numbers, say the one inside variable 'a', inside 'temp'.
2. then place the value of 'b' inside 'a'.
3. Put previous value of 'a', now placed inside 'temp', into 'a'.
In code it will look like this:
SWAP_NUMBERS(int a, int b) //a and b are given as parameters
temp = a //step 1.
a = b //step 2.
b = temp //step 3.
now (even though you didn't ask but you might find it interesting), there is another way to swap to numbers without using the temp variable. With a simple math trick you can do the swap:
SWAP_NUMBERS_2(int a, int b) //a and b are given as parameters
a = a + b;
b = a - b; //now b has the value of a.
a = a - b; //now a has the value of b.
Hope that this helps you, and if it does, just mark the thread as solved :)
To swap 2 numbers you will need 3 variables like int a ,int b and int temp.
1) First you have to initialize : a=10 , b=20 and temp=0;
2) Here temp is a temporary variable which will be used to pass the value.
1.temp=a;// Here the value of temp is 10(value of a).
2.a=b;// Here the value of a is 20(value of b).
3.b=temp;// Here the value of b is 10(value of temp).
3) Now print a and b.
you will get the output:
That will work for very small numbers, but not for large numbers because a+b will cause data overflow, and the result of that is undefined behavior.
Correct, it will work only for a+b <= Integer.MAX_VALUE. You can't say that this is "only for small numbers" though - I personally know a lot of numbers that are considered pretty huge that their sum is still less then 2^31-1 :)
XOR excludes floating point numbers. It's a bitwise operation and will work only on integers. I suppose you could treat the memory where the float is stored as just bytes and do it, but most compilers will complain if you try to do it directly.