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

Home > Algorithms
Swap (Posted on 2004-01-02) Difficulty: 2 of 5
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.

  Submitted by Brian Smith    
Rating: 3.2857 (7 votes)
Solution: (Hide)
The solution I originally intended was:

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

Others have suggested using XOR, since addition and subtraction can produce overflows

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

Comments: ( You must be logged in to post comments.)
  Subject Author Date
Sophisticated programming or Mathbrianjn2004-01-08 01:26:40
re: solutionFederico Kereki2004-01-05 11:07:48
Solution?Stereo2004-01-05 00:43:04
solution...sunny2004-01-04 18:29:43
QuestionNo Math?Richard2004-01-02 21:51:47
re(2): other solutionsRichard2004-01-02 21:47:58
re: other solutionsTristan2004-01-02 20:25:50
Solutionother solutionsCharlie2004-01-02 17:03:48
re: solutionGamer2004-01-02 16:10:22
Nice!stan2004-01-02 16:04:54
Solutionsolutionrerun1412004-01-02 14:48:46
Please log in:
Login:
Password:
Remember me:
Sign up! | Forgot password


Search:
Search body:
Forums (1)
Newest Problems
Random Problem
FAQ | About This Site
Site Statistics
New Comments (6)
Unsolved Problems
Top Rated Problems
This month's top
Most Commented On

Chatterbox:
Copyright © 2002 - 2024 by Animus Pactum Consulting. All rights reserved. Privacy Information