:: [intv] swap two numbers w/o using temp ::
HOME


[Date Prev][Date Next][Date Index]

[intv] swap two numbers w/o using temp


//---------------main.cpp-----------
//Problem: Swap two variables without using temp.
//Save as: main.cpp, compile as: g++ -o main main.cpp

#include <iostream>

using namespace std;

int main (){
  int a = 10;
  int b = 5;

  cout << "Before: a = " << a << " b = " << b << endl;
  a = a ^ b;
  b = b ^ a;
  a = a ^ b;

  cout << "After: a = " << a << " b = " << b << endl;


//OR

  a = a + b;
  b = a - b;
  a = a - b;
  cout << "After: a = " << a << " b = " << b << endl;


}

//---------------main.cpp-----------


Comments and corrections are appreciated and can be sent to papers@mia.ece.uic.edu. Click here for ©opyright information.