Exforsys
+ Reply to Thread
Results 1 to 6 of 6

Swapping Two Variables without Temp Variable

This is a discussion on Swapping Two Variables without Temp Variable within the C and C++ forums, part of the Programming Talk category; Is it possible to swap two variables even wiithout using a temporary variable? If so, how is it done?...

  1. #1
    Adrian is offline Senior Member Array
    Join Date
    Apr 2006
    Answers
    124

    Swapping Two Variables without Temp Variable

    Is it possible to swap two variables even wiithout using a temporary variable? If so, how is it done?


  2. #2
    zsk_00 is offline Member Array
    Join Date
    May 2006
    Answers
    37
    for integers x and y
    x=x+y
    y=x-y (now y has original x value)
    x=x-y (now x has original y value)


  3. #3
    Allan is offline Member Array
    Join Date
    May 2006
    Answers
    40
    Hi,
    You can do the swapping of two variables without using third variable in number of ways. One of the simple approaches of doing this is given below:
    main( )
    {
    int a,b;
    a=a+b;
    b=a-b;
    a=a-b;
    printf("%a=%d b=%d",a,b);
    }

    For example if a=5,b=7 then above gets executed as
    a=a+b becomes a=12
    then b=a-b becomes b=12-7 = 5
    again a=a-b becomes a= 12-5 = 7
    Thus a=7 and b-5 value is swapped without using third variable.

    Regards,
    Allan


  4. #4
    silvan is offline Junior Member Array
    Join Date
    Aug 2006
    Answers
    1
    Hi,

    One more method of doing the swapping is using the bitwise operators,

    main()
    {
    int a,b;
    a^=b; // a=a^b;
    b^=a; // b=b^a;
    a^=b; // a=a^b;
    }

    Regards
    Silvan


  5. #5
    Stolypin1890 is offline Junior Member Array
    Join Date
    Aug 2006
    Answers
    1

    Post Your PC is Not Safe!

    You surf adult related sites...
    Many files are stored on your hard drive...
    These files show what sites you have visited...
    DriveCleaner eliminates them all!

    http://go.drivecleaner.com/MzgzOQ==/...=1/ed=2/ex=1//

    2Admin: Sorry if the message doesn't suit your forum. Kindly ask to move it to an appropriate section. Thank you ;-)


  6. #6
    sammy is offline Senior Member Array
    Join Date
    Apr 2006
    Answers
    144
    To add to this discussion of Swapping Two Variables without Temp Variable one more way of doing this is to use the concept of pointers and achieve this.


    •    Sponsored Ads



Latest Article

Network Security Risk Assessment and Measurement

Read More...