12,357,105 members (76,722 online)
Rate this:
See more:
hi can any one tell me ..
is it possible value swap b/w two variables with out third variable...?
Posted 26-Sep-12 1:56am
Edited 26-Sep-12 2:45am
TorstenH.34.9K
v2

Rate this:

## Solution 1

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
Rate this:

## Solution 2

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]
v3
Rate this:

## Solution 3

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.
Mohibur Rashid 26-Sep-12 8:48am

not a good one
Rate this:

## Solution 4

#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;
}
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)

Top Experts
Last 24hrsThis month
 Sergey Alexandrovich Kryukov 273 OriginalGriff 245 Jochen Arndt 235 Richard Deeming 205 ErBhati 195
 OriginalGriff 10,073 Sergey Alexandrovich Kryukov 6,739 Dave Kreskowiak 3,317 ppolymorphe 2,467 Karthik Bangalore 2,381