Blogs on truth, technology, food, linux, leisure, experiences, adventure, romance, friends etc !

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;
}

____________________________________________________________________________
____________________________________________________________________________

Comments on: "Swap two numbers without a ‘=’ operator" (2)

  1. 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);

    }

  2. Yup dude. There are many other ways

Leave a comment for: "Swap two numbers without a ‘=’ operator"