Sunday, February 19, 2012

SWAPPING-VERY IMPORTANT LOGIC


#include<iostream>
using namespace std;

void approach1(int& a, int& b)
{
  cout<<"\nApproach 1"<<endl;
  a^=b^=a^=b;
}

void approach2(int& a, int& b)
{
  cout<<"\nApproach 2"<<endl;
  //b=(a+b)-(a=b); - This should work but doesnt, why?  a =((a = a + b) - (b = a - b)); 
}

void approach3(int& a, int& b)
{
  cout<<"\nApproach 3"<<endl;
  a = ((a = a * b) / (b = a / b));
}



int main()
{
  int a = 13, b = 29;
  cout<<"\nOriginal"<<endl;
  cout<<"a = "<<a<<", b = "<<b<<endl;

  approach1(a, b);
  cout<<"a = "<<a<<", b = "<<b<<endl;

  a = 13, b = 29;
  approach2(a, b);
  cout<<"a = "<<a<<", b = "<<b<<endl;

  a = 13, b = 29;
  approach3(a, b);
  cout<<"a = "<<a<<", b = "<<b<<endl;

  return 0;
}

1 comment:

  1. Hey this is the new logics I found..N I posted it coz It may be somewhat beneficial for most of those who check it...

    ReplyDelete