How can I swap two variables without using a third variable?Can u plz tell me the logic behind it..?

Showing Answers 1 - 7 of 7 Answers

PraveenReddy

  • Sep 28th, 2005
 

Add two variables and assign the value into First Variable.Subtract the Second value with the Resul Value. and assign to Second Variable.Subtract the Result of First Variable With Result of Second Variable and Assign to First Variable.EX:Int a=5,b=10;a=a+b; b=a-b; a=a-b;

  Was this answer useful?  Yes

gpp

  • Oct 19th, 2005
 

xor the 2 variables to swap without using a third variable.

example x=A, y=B

  x = x ^ y ;
  y = x ^ y ; //y=A after this step
  x = x ^ y ; //x=B after this step

  Was this answer useful?  Yes

Ashwini

  • Oct 26th, 2005
 

step1>: a=a+b; step2>:b=a-b;step3>:a=a-b;

 

  Was this answer useful?  Yes

Devidas Sonawane

  • Oct 26th, 2005
 

U can use out following Options.

Option 1) a=a*b; b=a/b; a=a/b;

Option 2) a=a/b; b=a*b; a=b*a;

Option 3) a=a-b; b=a+b; a=a+b;

Option 4) a=a+b; b=a-b; a=a-b; 

Debasish Dutta Roy

  • Jan 16th, 2006
 

Always use the XOR operation as the answer provided in solution 1 can produce overflows

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions