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.
sir please have a look at my prog:
ReplyDelete#include
using namespace std;
int main()
{
int a=6,b=2;
cout<<"original:"<<endl<<"a="<<a<<endl<<"b="<<b<<endl;
a-=(b=(a+=b)-b);
cout<<"new values:"<<endl<<"a="<<a<<endl<<"b="<<b;
getchar();
return 0;
}
Vaibhav, your approach is fine as its the same as approach 2:
ReplyDeletea =((a = a + b) - (b = a - b));
I generally tend to discourage people writing it this way as it can make the code unreadable. Otherwise its fine.
ok sir i'll keep that in mind while makin future programs...
ReplyDeletethanks for for the feedback
a^=b^=a^=b;
ReplyDeletea =((a = a + b) - (b = a - b));
a = ((a = a * b) / (b = a / b));
All of them cause Undefined Behaviour - variable is modified twice between consecutive sequence points.
ap: Which compiler are you using?
ReplyDeleteIt also depends on how and where you use these statements. Did you use my program as it is and it complained?
@ //b=(a+b)-(a=b); - This should work but doesnt, why?
ReplyDeletethis should be
b=(a-b)+(a=b);
This does not seem like a relevant interview question to me. I'd prefer my hires NOT use this because it's so cryptic. The ability to write clean code and express your thoughts concisely would be my number one criteria, not esoteric bit-wise operations that could be Googled in 30 seconds.
ReplyDeletea=a+b-(b=a) ;
ReplyDeleteI make it even more interesting
ReplyDeletethe variables are of 8bit n unsigned