Monday 24 September 2012

SWAPPING, 4 ways to swap in C/C++



SWAPPING, 4 WAYS TO SWAP IN C OR C++

DISCLAIMER: Though program(s) mentioned here is a working program and also, I have tried my best to make this content error free, but still I do not claim that every concept mentioned here is correct. Therefore, content available here is not meant for primary source of learning.

WHAT IS SWAPPING?


Swap means to exchange. Therefore in C/C++ swapping of variables simply means exchanging the value of one variable with another variable.


Let us understand this concept with an example:

            Let A and B be two variables and they contain values A=5 and B=10
            Then after swapping   A=10 and B=5. (Note than values have been exchanged.)


In this blog I will be using int data type for swapping. You may use different data type for swapping. 

HOW TO SWAP

METHOD 1. USING THREE VARIABLES


This is the simplest method to swap values. This method uses three variables, of which two are those variable whose values are going to be swapped and third one is a temporary variable which helps us in doing this.
let us see how to implement it in C/C++

int A=5;
int B=10;
int temp;
///////Now see how to swap////////
temp=A;
A=B;
A=temp;
//////////done swapping///////////
See How to Swap


METHOD 2. USING TWO VARIABLES AND ADDITION/SUBTRACTION OPERATION

In this method we will use only two variables two swap the values but before jumping to two variable method let us understand it using three variables.

Let there are three variables A, B, and C. If C stores the sum of A and B
i.e. C=A+B then 


if you subtract A from C you will get B and,
if you subtract B from C you will get A.

See how…

If  C = A + B  then
C – A = (A+B) – A = B  or simply C – A = B
And, C – B = (A+B) – B = A or simply C – B = A

Let us understand it using numeric values

If A=5, B=10 therefore C=A+B=15
then C – A = 15 – 5 = 10
and C – B = 15 – 10 = 5


Now let us write a c code snippet for this


///So let us write in form of C/C++ program///
int A=5, B=10, C;
C=A+B;    //C=5+10=15
A=C-A;    //A=15-5=10
B=C-B;    //B=15-10=5
/////done swapping/////////

>>NOW USING TWO VARIABLE

Above program can simply be written using two variables only. There is no need to introduce a third variable C. Just see the changes in code below.

///So let us write in form of C/C++ program///
int A=5, B=10;
A=A+B;    //A=5+10=15
B=A-B;    //B=15-10=5 (B changed to 5)
A=A-B;    //A=10, as new value of B is 5 so A-B=15-5=10
/////done swapping/////////

Try to figure out changes, it is very simple. I have written comments for your convenience.

METHOD 3. USING TWO VARIABLES AND MULTIPLICATION/DIVISION OPERATION

This method is similar to above method of swapping, except that it uses multiplication and division. For this method just make a little change i.e. replace + for * and – for /. Concept behind doing this remains same.


///So let us write it in form of C/C++ program///
int A=5, B=10;
A=A*B;    //A=5*10=50
B=A/B;    //B=50/10=5 (B changed to 5)
A=A/B;    //A=10, as new value of B is 5 so A/B=50/5=10
/////done swapping/////////

Note : This method is not much reliable as sometime when you multiply two numbers(large numbers) you will get very large product which may go out of range of the data type used and thus we wont be able to swap those numbers.


METHOD 4. USING TWO VARIABLES AND XOR OPERATION

This method may appear quite complicated to you. But if you have some knowledge of XOR (binary operation) then you will find that it is very simple. If you do not have any idea about XOR operation then I will recommend you to refer a book on C or C++ programming and read about bitwise operators in it or search in google. You can also read about Boolean Algebra. 
Let a there are three variables A, B, and C. If C stores the XOR of A and B

i.e. C=A XOR B then
if you XOR A to C you will get B and,
if you XOR B to C you will get A.

See how…

If  C = A XOR B  then
C XOR A = (A XOR B) XOR A = B  or simply C XOR A = B
And, C XOR B = (A XOR B) XOR B = A or simply C XOR B = A

Let us understand it using numeric values

If A=5, B=10 therefore C=A XOR B = 15  (use windows calculator to calculate)
then C XOR A = 15 XOR 5 = 10   (use windows calculator to calculate)
and C XOR B = 15 XOR 10 = 5

Now let us write a c code snippet for this(using two variable only):

///So let us write in form of C/C++ program///
int A=5, B=10;
A=A^B;    //A=5^10=15
B=A^B;    //B=15^10=5
A=A^B;    //A=15^5=10
/////done swapping/////////

>>PROGRAM OF C++, THAT USES ABOVE CONCEPTS
>>>>>Version 1 without using functions, for friends who have just started learning C++ and haven’t learnt about functions yet.
#include<iostream.h>
#include<conio.h>

int main()
{
     int x,y;
     cout<<"Enter two numbers :";
     cin>>x>>y;

     cout<<"\n\nBefore swapping x="<<x<<" y="<<y;
          int temp;
          temp=x;
          x=y;
          y=temp;
     cout<<"\nAfter swapping  x="<<x<<" y="<<y;

     cout<<"\n\nBefore swapping x="<<x<<" y="<<y;
          x=x+y;
          y=x-y;
          x=x-y;
     cout<<"\nAfter swapping  x="<<x<<" y="<<y;

     cout<<"\n\nBefore swapping x="<<x<<" y="<<y;
          x=x*y;
          y=x/y;
          x=x/y;
     cout<<"\nAfter swapping  x="<<x<<" y="<<y;

     cout<<"\n\nBefore swapping x="<<x<<" y="<<y;
          x=x^y;
          y=x^y;
          x=x^y;
     cout<<"\nAfter swapping  x="<<x<<" y="<<y;
     getch();
     return 0;
}

>>>>>>>Version 2 for friends who know about functions.
#include<iostream.h>
#include<conio.h>
void swapmethod1(int &a, int &b)
{
     int temp;
     temp=a;
     a=b;
     b=temp;
}
void swapmethod2(int &a, int &b)
{
     a=a+b;
     b=a-b;
     a=a-b;
}
void swapmethod3(int &a, int &b)
{
     a=a*b;
     b=a/b;
     a=a/b;
}
void swapmethod4(int &a, int &b)
{
     a=a^b;
     b=a^b;
     a=a^b;
}
int main()
{
     int x,y;
     cout<<"Enter two numbers :";
     cin>>x>>y;

     cout<<"\n\nBefore swapping x="<<x<<" y="<<y;
     swapmethod1(x,y);
     cout<<"\nAfter swapping  x="<<x<<" y="<<y;

     cout<<"\n\nBefore swapping x="<<x<<" y="<<y;
     swapmethod2(x,y);
     cout<<"\nAfter swapping  x="<<x<<" y="<<y;

     cout<<"\n\nBefore swapping x="<<x<<" y="<<y;
     swapmethod3(x,y);
     cout<<"\nAfter swapping  x="<<x<<" y="<<y;

     cout<<"\n\nBefore swapping x="<<x<<" y="<<y;
     swapmethod4(x,y);
     cout<<"\nAfter swapping  x="<<x<<" y="<<y;

     getch();
     return 0;
}

>>PROGRAM OF C, THAT USES ABOVE CONCEPTS
>>>>>Version 1 without using functions, for friends who have just started learning C++ and haven’t learnt about functions yet.
 
#include<stdio.h>
#include<conio.h>

int main()
{
    int x,y;
    int temp; //used for swapping
    printf("Enter two numbers :");
    scanf("%d%d",&x,&y);

    printf("\n\nBefore swapping x=%d y=%d",x,y);
        temp=x;
        x=y;
        y=temp;
    printf("\nAfter swapping  x=%d y=%d",x,y);

    printf("\n\nBefore swapping x=%d y=%d",x,y);
        x=x+y;
        y=x-y;
        x=x-y;
    printf("\nAfter swapping  x=%d y=%d",x,y);

    printf("\n\nBefore swapping x=%d y=%d",x,y);
        x=x*y;
        y=x/y;
        x=x/y;
    printf("\nAfter swapping  x=%d y=%d",x,y);

    printf("\n\nBefore swapping x=%d y=%d",x,y);
        x=x^y;
        y=x^y;
        x=x^y;
    printf("\nAfter swapping  x=%d y=%d",x,y);

    getch();
    return 0;
}



>>>>>>>Version 2 for friends who know about functions.

#include<stdio.h>
#include<conio.h>

void swapmethod1(int *a, int *b)
{
    int temp;
    temp=*a;
    *a=*b;
    *b=temp;
}
void swapmethod2(int *a, int *b)
{
    *a=(*a)+(*b);
    *b=(*a)-(*b);
    *a=(*a)-(*b);
}
void swapmethod3(int *a, int *b)
{
    *a=(*a)*(*b);
    *b=(*a)/(*b);
    *a=(*a)/(*b);
}
void swapmethod4(int *a, int *b)
{
    *a=(*a)^(*b);
    *b=(*a)^(*b);
    *a=(*a)^(*b);
}

int main()
{
    int x,y;
    printf("Enter two numbers :");
    scanf("%d%d",&x,&y);

    printf("\n\nBefore swapping x=%d y=%d",x,y);
    swapmethod1(&x,&y);
    printf("\nAfter swapping  x=%d y=%d",x,y);

    printf("\n\nBefore swapping x=%d y=%d",x,y);
    swapmethod2(&x,&y);
    printf("\nAfter swapping  x=%d y=%d",x,y);

    printf("\n\nBefore swapping x=%d y=%d",x,y);
    swapmethod3(&x,&y);
    printf("\nAfter swapping  x=%d y=%d",x,y);

    printf("\n\nBefore swapping x=%d y=%d",x,y);
    swapmethod4(&x,&y);
    printf("\nAfter swapping  x=%d y=%d",x,y);

    getch();
    return 0;
}