Hey hi all, I would like, to know some suggestion on my problem. The question is that how can I swap two numbers without using a third temporary variable? I aam waiting for the response, if you have any answer about tit then reply me back.
Hey hi all, I would like, to know some suggestion on my problem. The question is that how can I swap two numbers without using a third temporary variable? I aam waiting for the response, if you have any answer about tit then reply me back.
I think that yes, this is possible to swap two numbers without using a third temporary variable. For doing this thing you might be need to take extra thread on it.
Ok, assume that there are two numbers like x and y then:
x = x+y
y=x-y
x=x-y.
sorry friend, but I am getting confused with your question, will you don’t have b any book or some thing else, I think that you have created a thread on this topic.
According to me, the code for the swapping two number without using the first number is given as follows:
a= a^b;
b = b^a;
a = a^b;
In this case I will ask you for the operating system which you are using for your query. The above reply will working this case if you are using the C or C++, but also in this case try to not use one line XOR technique, because this thing is undefined and not portable.
If it's Python:
v1, v2 = v2, v1
In your case you can also take the help of the pointers. Pointers are the variable which stores the memory location of the variable. With the help of the pointers I am sure that you are able to swap the variable without using the third variable.
Hey in this case, I still think that it will require another variable, unless the address of two variables is consecutive. I am telling this thing because as soon as you will apply swap on pointer variable at this time the previous value will be lost and also you cannot swap both the variable in the single operation. So for the swapping I will suggest you to follow the approach that nims11 provided. Hope this will help you.
Bookmarks