Couple of weeks back I was interviewing a fresh graduate. Even though they are taught programming, I am not sure if they take it seriously and learn or practice it well. One of the questions I asked was to swap 2 numbers without using a temp variable.
Looking back now, I think it may be a bigger challenge to ask to swap numbers without using a temp variable and in one line. Below are my three different approaches but I would advise you to try it yourself before looking at the answer.
//Program to swap 2 numbers without using 3rd variable and in one line
//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#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;
}
The output is as follows:
Agreed that the above would be applicable only for integers.