i m trying to swap values of 2 varable without using 3rd variable but

i m trying to swap values of 2 varable without using 3rd variable but not getting
help me here expertzz
1
2
3
4
5
6
7
8
9
10
#include<conio.h>
#include<iostream>
using namespace std;
void main()
{int A,B;
A=10,B=20;
	A=(A+B-(B=A));
cout<<A<<" \n"<<B;
	getch();
}
closed account (o3hC5Di1)
Hi there,

Use std::swap(A, B); :)

All the best,
NwN
I think not a programmer aproach ...!!
in my view it is not a logical way
This works for integral types only:

1
2
3
4
5
6
7
8
int A = 10;
int B = 20;

A ^= B;
B ^= A;
A ^= B;

cout << A << "  " << B;


Though I agree with NwN. Use std::swap()
closed account (o3hC5Di1)
Awais Tahir wrote:
I think not a programmer aproach ...!!
in my view it is not a logical way


Could you please explain what you mean by that?

@Disch, that's clever, I always forget about those binary operators.

All the best,
NwN
what about this
A=(A+B-(B=A))
Awais: That is undefined. You must not modify a variable (in this case, B) and attempt to read it in the same sequence.

It wouldn't even work if it worked as you think it does. As soon as you do (B=A), you permanently lose the original value of B.
But condition is not to Use Third var
as we do
temp=A;
A=B;
B=temp;


swapping with using 2 var
I know. I already posted a solution that does not use a 3rd var. See my previous post.
NwN gave you a perfect example using a standard function and Disch give you a perfect example using bitwise operations.

What's wrong with either of those?
Sorry dears i am not getting ....
plz write a simple code so it would be easy to catch ur ideas
I already did write a simple example.....


1
2
3
4
5
6
7
8
int A = 10;
int B = 20;

A ^= B;
B ^= A;
A ^= B;

cout << A << "  " << B;


If you are looking for an explanation....:

The XOR operator (^) has the interesting property of being self-undoable. That is:
1
2
x ^ x == 0 // for all values of x
(x ^ z) ^ x == z  // for all values of x or z 


This basically allows you to "merge" two numbers.

With this in mind, the code above operates like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int A = 10;
int B = 20;

// this 'merges' B into A.  As a result, A==10^20
A ^= B;

// this merges the new value of A (10^20) into B
//  since B already contains 20, this means B == (10^20^20).
//  The XOR then cancels the 20's out, meaning B == 10
B ^= A;

// now we merge the new value of B (10) into A (10^20)
//  this means A == (10^10^20)
//  again, the XOR cancels out the 10's, leaving A == 20
A ^= B;

// A and B have been effectively swapped.  No 3rd variable used. 
O thanks dear...
i get this point
A = A+B;
B = A-B;
A = A-B;

edit: Made a small diagram; could help:

http://s2.postimage.org/6mnutol9l/swap.jpg
Last edited on
@Awais Tahir, keep in mind that not using a third variable is a bad thing, it's slower to execute and harder to understand, although it makes for a nice beginner puzzle.
THANKZ ALL OF U....!!
Topic archived. No new replies allowed.