11 June, 2008

Swap two numbers without a '=' operator

Came across an interesting problem of swapping two numbers without using '=' operator. I thought of this approach. It's little lengthy and can be modified I guess.
____________________________________________________________________________
____________________________________________________________________________

#include
static int counter;
int main()
{
int a,b;
printf("Enter two numbers");
scanf("%d%d",&a,&b);

if(a>b)
{
switch ((a-b)%2)
{
case 0 :while((a-b))
{
counter++;
a--;
b++;
}
while (counter >0)
{
counter--;
a--;
b++;
}
printf("\nThe swapped set : %d\t%d",a,b);
break;
case 1 :while((a-b-1))
{
counter++;
a--;
b++;
}
counter++;
while (counter >0)
{
counter--;
a--;
b++;
}
printf("\nThe swapped set : %d\t%d",a,b);
break;
}
}

else
{
switch ((b-a)%2)
{
case 0 :while((b-a))
{
counter++;
a++;
b--;
}
while (counter >0)
{
counter--;
a++;
b--;
}
printf("\nThe swapped set : %d\t%d",a,b);
break;
case 1 :while((b-a-1))
{
counter++;
a++;
b--;
}
counter++;
while (counter >0)
{
counter--;
a++;
b--;
}
printf("\nThe swapped set : %d\t%d",a,b);
break;
}
}
return 0;
}

____________________________________________________________________________
____________________________________________________________________________

3 readers commented:

aknoob said...
This comment has been removed by the author.
aknoob said...

We have other options instead of using =.Similar semantics are observed by function calls while passing params.Also We can use a notion of copy consrtuctor which is present by default in C++.To use that just write a wrapper around Int..

class Int{

int num;
public:
Int(){memcpy(&num,0);};
Int(int a){memcpy(&num,&a);};

}

main()
{

Int a,b;
Int c(a);
Int a(b);
Int b(a);

}
class Int{

int num;
public:
Int(){memcpy(&num,0);};
Int(int a){memcpy(&num,&a);};

}

main()
{

Int a(4),b(5);
Int c(a);
Int a(b);
Int b(a);

}

rakesh said...

Yup dude. There are many other ways