471,072 Members | 1,000 Online

# interchange two number

17
is it possibe that interchange two no.
using only two integer in c not in c++
Sep 6 '06 #1
8 3247
is it possibe that interchange two no.
using only two integer in c not in c++
Yes, definitely.
Use XOR property, ie

p = p XOR b
changes p according to value of b

p = p XOR b
you get back the original p.
Sep 6 '06 #2
anirban
17
my problem is following
i give input of two no.

a=5
b=7
both are integer

my required output will be
a = 7
b= 5

without using third variable
Sep 6 '06 #3
int a, b;
a= 5;
b= 7;

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

this will give the requied solution.. there are couple of more solutions to this..
the XOR suggested above is also correct.!! :)
Sep 6 '06 #4

a= a*b;
b=a/b;
a=a/b;

will also yeild the same desired output...!!
Sep 6 '06 #5
Always use XOR operations.

Let us assume that both a and b are integers and suppose maximum value that an integer can store be 1000.

let a=500 and b=700 then the methods suggested above will fail to give the right answers.

so the correct way is to use the XOR operations
Sep 6 '06 #6
Always use XOR operations.

Let us assume that both a and b are integers and suppose maximum value that an integer can store be 1000.

let a=500 and b=700 then the methods suggested above will fail to give the right answers.

so the correct way is to use the XOR operations

yes you are very much right.. i was just considering the case of the particular input which he has mentioned.
Sep 6 '06 #7
yes it is possible

the deal is swapping

use pointers
or
just
copy
temp=a;
a=b;
b=temp;// temp is temporary variable
Sep 6 '06 #8
anirban
17
int a, b;
a= 5;
b= 7;

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

this will give the requied solution.. there are couple of more solutions to this..
the XOR suggested above is also correct.!! :)

thanks your solution help me to solve the problem
Sep 7 '06 #9