471,072 Members | 1,000 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,072 software developers and data experts.

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
to add something more..

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
asamum
1
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

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

8 posts views Thread by EAS | last post: by
4 posts views Thread by Sreejith K | last post: by
11 posts views Thread by don | last post: by
3 posts views Thread by Bernhard Hidding | last post: by
2 posts views Thread by Hank Reed | last post: by
momotaro
3 posts views Thread by momotaro | last post: by
reply views Thread by =?Utf-8?B?S3VydA==?= | last post: by
reply views Thread by leo001 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.