Thread: swapping of two numbers

  1. #1
    Registered User baffleddreams's Avatar
    Join Date
    Aug 2010
    Location
    India
    Posts
    15

    swapping of two numbers

    i want to swap two numbers without using a third variable && an arithmetic operator

  2. #2
    Registered User
    Join Date
    Jan 2010
    Posts
    34
    Do you mean
    A=B; and B=A; without using C?

  3. #3
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    I don't know that that can be done. I'm fairly certain than any library that would swap two numbers for you would just be doing the third variable and assignment operator under the surface.

    What is that you're trying to accomplish by eliminating the third variable? Just less memory usage? In the context of a real program, the third variable is very insignificant.

  4. #4
    Registered User
    Join Date
    Aug 2010
    Location
    Poland
    Posts
    733
    Yes, there is an algorithm. If I remember it went like this:

    a = 5;
    b = 2;
    // now 5,2

    a -= b
    // now 3,2

    b += a
    // now 3,5

    a = b - a;
    // now 2,5


    But as I remember it didn't work with all numbers - ???

    EDIT:

    What is that you're trying to accomplish by eliminating the third variable? Just less memory usage? In the context of a real program, the third variable is very insignificant.
    I'm sure it's his homework ...
    Last edited by kmdv; 08-25-2010 at 07:48 AM.

  5. #5
    Registered User
    Join Date
    Aug 2010
    Posts
    35
    Why?

    Code:
    void swap(int *a, int *b) {
        *b += *a;
        *a = *b-*a;
        *b -= *a;
    }
    Pointless, but it works.

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    That is, unless arithmetic overflow or underflow causes a trap on your machine.

    The whole exercise is pointless. Tutors who think this kind of "spoon on your nose" magic trick is worth knowing should be avoided.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Matching numbers
    By kirksson in forum C Programming
    Replies: 7
    Last Post: 07-23-2008, 01:51 PM
  2. Question about random numbers
    By Kempelen in forum C Programming
    Replies: 2
    Last Post: 07-02-2008, 06:28 AM
  3. the definition of a mathematical "average" or "mean"
    By DavidP in forum A Brief History of Cprogramming.com
    Replies: 7
    Last Post: 12-03-2002, 11:15 AM
  4. Line Numbers in VI and/or Visual C++ :: C++
    By kuphryn in forum C++ Programming
    Replies: 2
    Last Post: 02-10-2002, 10:54 PM
  5. A (complex) question on numbers
    By Unregistered in forum C++ Programming
    Replies: 8
    Last Post: 02-03-2002, 06:38 PM