Click here to Skip to main content
15,884,298 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
How to swap two numbers without using third variable?
Posted
Updated 15-Jan-18 19:00pm
Comments
Richard MacCutchan 5-Oct-10 17:44pm    
Why would you care?
Dylan Morley 7-Oct-10 9:25am    
^ because it's a question on his homework?
Yusuf 7-Oct-10 13:33pm    
why can't you figure your own homework. Give me 10 dollars I give you back 1 dollar. You see we swapped dollars with no third party involved.

Given:

int a = 1;
int b = 2;

You can do this:
a = a + b;
b = a - b;
a = a - b;

or this:
b = a ^ b;
a = b ^ a;
b = a ^ b;

or just use the std:swap method.
 
Share this answer
 
v2
Comments
thatraja 7-Oct-10 9:19am    
Hi john, i just replaced x & y into a & b in your answer which you have forgot, But later i found that i should have changed just the variables a & b into x & y. :-) cheers
Only one of the above choices will protect against overflow/underflow.
b = a ^ b;
a = b ^ a;
b = a ^ b;
 
Share this answer
 
One more to the list:
// x:4; y:7  
x = x*y;  // 4*7  
y = x/y;  // 28/7 = 4  
x = x/y;  // 28/4 = 7  
 
Share this answer
 
//why to go for three lines of code when i have single line code

//int a=20;b=10

b=(a+b)-(a=b);
 
Share this answer
 
x XOR y
y XOR x
x XOR y

(XOR == Exclusive OR for those not familiar with PDP-10 assembly code :))

It is an exercise for the student to write than in their favorite language or C++ or Java or whatever other language tags you feel like adding to this question.
 
Share this answer
 
Dear that's so symple use that code

a=a+b;
b=a-b;
a=a-b;


thats better way of swapping......
without use temporary variable.
 
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