Click here to Skip to main content
11,433,220 members (59,909 online)
Rate this: bad
good
Please Sign up or sign in to vote.
See more: Java Homework
hi can any one tell me ..
is it possible value swap b/w two variables with out third variable...?
Posted 26-Sep-12 2:56am
Edited 26-Sep-12 3:45am
TorstenH.34.7K
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)



Advertise | Privacy | Mobile
Web01 | 2.8.150428.2 | 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