Click here to Skip to main content
11,704,107 members (64,478 online)
Rate this: bad
good
Please Sign up or sign in to vote.
See more: Java
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.8K
v2
Rate this: bad
good
Please Sign up or sign in to vote.

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
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

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]
  Permalink  
v3
Rate this: bad
good
Please Sign up or sign in to vote.

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.
  Permalink  
Comments
Mohibur Rashid at 26-Sep-12 8:48am
   
not a good one
Rate this: bad
good
Please Sign up or sign in to vote.

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;
}
  Permalink  
Comments
TorstenH. at 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 at 9-Oct-12 12:44pm
   
That was code in C language. May I knw what is wrong in it.
TorstenH. at 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)

  Print Answers RSS
0 Maciej Los 520
1 OriginalGriff 500
2 Sergey Alexandrovich Kryukov 381
3 Andy Lanng 294
4 F-ES Sitecore 220
0 OriginalGriff 8,784
1 Sergey Alexandrovich Kryukov 7,843
2 CPallini 5,107
3 Maciej Los 4,726
4 Mika Wendelius 3,606


Advertise | Privacy | Mobile
Web04 | 2.8.150819.1 | Last Updated 8 Oct 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100