12,952,725 members (37,320 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
Updated 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)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Top Experts
Last 24hrsThis month
 OriginalGriff 295 RickZeeland 125 ppolymorphe 100 CPallini 90 AdvancedDNA 85
 OriginalGriff 6,289 CHill60 3,490 Maciej Los 3,103 Jochen Arndt 1,975 ppolymorphe 1,900

Advertise | Privacy | Mobile
Web02 | 2.8.170525.1 | Last Updated 8 Oct 2012