Click here to Skip to main content
15,886,026 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi can any one tell me ..
is it possible value swap b/w two variables with out third variable...?
Posted
Updated 26-Sep-12 2:45am
v2

C#
#include <stdio.h>
int main() {
int i = 65;
int k = 120;
printf("\n value of i=%d k=%d before swapping", i, k);
i = i ^ k;
k = i ^ k;
i = i ^ k;
printf("\n value of i=%d k=%d after swapping", i, k);
return 0;
}
 
Share this answer
 
Comments
TorstenH. 8-Oct-12 9:49am    
wrong language. Also homework - don't know how it#s handled in the C-Section, but in the Java section we don't do homework.
N Shiva 9-Oct-12 12:44pm    
That was code in C language. May I knw what is wrong in it.
TorstenH. 9-Oct-12 13:02pm    
it's C. does it need more ;-)
(PS: I did not downvote)
I would be inclined to say no:

You need somewhere to store one of the values i.e. You can't write b to w or w to b without first taking the value from the target pointer and storing it else where.

Otherwise, as soon you write w to b or visa versa you will have lost half the data you're looking to swap.
 
Share this answer
 
Comments
Mohibur Rashid 26-Sep-12 8:48am    
not a good one
No, you cannot do that. Why do you mind using the third variable?

[update]
It looks (see, for instance, Swapping content of 2 vars[^]) you actually can, but is less efficient (and it has, in my opinion some caveats).
[/update]
 
Share this answer
 
v3
int a=20, b=30;

// before swapping values are a= 20 and b=30


a = a+b ; // now a = 50 and b= 30
b = a-b; // now a = 50 and b = 20
a = a-b; // now a = 30 and b= 20


// after swapping values are a= 30 and b = 20
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900