All about flooble | fun stuff | Get a free chatterbox | Free JavaScript | Avatars
 perplexus dot info

 Swap (Posted on 2004-01-02)
In programming, a common task is to swap the values of two variables. Lines 40-60 of the program below perform the swap using a temporary variable (T).

10 A=123
20 B=456
30 PRINT A,B
40 T=A
50 A=B
60 B=T
70 PRINT A,B

Rewrite the program to swap the values in A and B without using a temporary variable.

Note: The new program will not require sophisticated programming or complex math.

 See The Solution Submitted by Brian Smith Rating: 3.2857 (7 votes)

Comments: ( Back to comment list | You must be logged in to post comments.)
 other solutions | Comment 4 of 11 |
Since this looks like it was written in GWBASIC (aka BASICA), you could use

SWAP A,B

but that's cheating, and also internally probably uses a temporary variable.

The classic method is

A = A XOR B
B = A XOR B
A = A XOR B

This works in integers in Basic, but rerun141's answer allows floating point numbers with fractions also. In languages like C or C++, the XOR could be done on a byte-by-byte basis, avoiding loss of precision in non-integral floating-point numbers, and working with equal-sized strings as well.
 Posted by Charlie on 2004-01-02 17:03:48

 Search: Search body:
Forums (0)