4 Replies - 3835 Views - Last Post: 13 March 2017 - 03:30 AM

#1 frog   User is offline

  • unleashed
  • member icon

Reputation: 2
  • View blog
  • Posts: 683
  • Joined: 26-March 06

swap

Posted 11 August 2006 - 03:01 AM

Description: this program illustrartes two ways to swap two numbers one wof which would be known to all of us and another interesting way
#include<iostream>
using namespace std;

void swap1(int &a,int &b) //commonly used
{
   int temp;
   temp=a;
   a=b;
   b=temp;
}

void swap2(int &a,int &b)   //doesnt involve the use of a temporary variable
{
   a=a+b;
   b=a-b;
   a=a-b;
}

int main()
{
   int a,b;
   cout<<"enter two numbers :";
   cin>>a>>b;
   
   swap1(a,b);
   cout<<a<<"  "<<b;
   
   swap2(a,b);
   cout<<a<<"  "<<b;
   
   system("pause");
   return 0;
}


Is This A Good Question/Topic? 0
  • +

Replies To: swap

#2 jjhaag   User is offline

  • me editor am smartastic
  • member icon

Reputation: 48
  • View blog
  • Posts: 1,789
  • Joined: 18-September 07

Re: swap

Posted 20 November 2007 - 12:10 PM

Good demos. Second will only work if a+b doesn't overrun the limits of the int datatype.
Was This Post Helpful? 0
  • +
  • -

#3 Karel-Lodewijk   User is offline

  • D.I.C Addict
  • member icon

Reputation: 454
  • View blog
  • Posts: 864
  • Joined: 17-March 11

Re: swap

Posted 11 February 2012 - 02:47 AM

You might want to add xor swap to that list
Was This Post Helpful? 0
  • +
  • -

#4 vaibhawofficial   User is offline

  • New D.I.C Head

Reputation: 7
  • View blog
  • Posts: 13
  • Joined: 07-February 17

Re: swap

Posted 10 February 2017 - 03:55 PM

//DIFFERENT FUNCTIONS TO SWAP VARIABLES


//____________________________________________________________________________________
/*
funct uses one extra variable of that datatype to swap the value
call as:
swapUsingVar(variable1,variable2)
*/
template <typename K> void swapUsingVar(K &a, K &B)/>/>{
    K temp=a;
    a=b;
    b=temp;
    return;
}
//_____________________________________________________________________________________
/*this funct uses no new variable, but a+b should also be in datatype of a abd b
call as
swapNoVar(a,B)/>/>
*/
template <typename K> void swapNoVar(K &a,K &B)/>/>{
    a+=b;b=a-b;a=a-b;
}
//_____________________________________________________________________________________
/*XOR SWAP, works only for int and char 
call as
swapXOR(a,B)/>/>  //a and b are int or char
*/
void swapXOR (int &a, int &B)/>/>{
    a==b?:a^=b,b^=a,a^=b;
}

void swapXOR (char &a, char &B)/>/>{
    a==b?:a^=b,b^=a,a^=b;
}



Was This Post Helpful? 0
  • +
  • -

#5 Salem_c   User is online

  • void main'ers are DOOMED
  • member icon

Reputation: 2284
  • View blog
  • Posts: 4,376
  • Joined: 30-May 10

Re: swap

Posted 13 March 2017 - 03:30 AM

C++ has moved on from what amount to silly assembler level tricks.

Just use std::swap
http://en.cppreferen.../algorithm/swap
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1