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

____________________________________________________________________________
____________________________________________________________________________

Google Reader Yahoo Facebook Twitter Digg FriendFeed Delicious Google Translate

Read More
  • No Related Post

This entry was posted onJune 11th, 2008 at 5:36 pm. You can follow any responses to this entry through the RSS 2.0. You can Leave a response, or Trackback.

2 Responses

Comments(2)Trackbacks(0)

  1. Manish

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

    }

    June 20, 2008 12:02 pm | #1
  2. rakesh

    Yup dude. There are many other ways

    June 21, 2008 7:51 pm | #2

Leave a Reply

(Ctrl+Enter)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>