Different ways to swap values | Wave the world

Different ways to swap values

Hi friends,
                Today I'm going to talk on swapping concept. You all know how to swap but which is the fastest way to swap two variables values. What is swapping? It's mean to exchange values of one variable to another variable. I'm going to describe here three method to swap two variable. In first method we'll use a temporary variable that is used to store intermediate result. In second method we'll use addition and subtraction but no other variable and in the last method we use bitwise XOR operator. Lets take two variable named A,B.

A=10
B=20

after swapping

A=20
B=10

Method:1 (Swapping using temporary variable)
Here we have to take another variable temp. It is the simplest method to swapping values between variables.

temp=A;
A=B;
B=temp;

Method:2 (Swapping with Addition and Subtraction)
In this method we don't use another temporary variable. It can only swap numeric variable values and if the value stored in the variable is little less from its range then it will not work properly and will give incorrect answer. 

A=A+B;
B=A-B;
A=A-B;

Method 3 (Swapping using XOR bitwise operator)
It is the fastest method to swap two variables but it's not working on floating type variables and gives correct output on character and integer type variables.

A=A^B;
B=A^B;
A=A^B;

Here is the full program,

#include<stdio.h>
#include<conio.h>
int main()
{
int a,b,temp;
clrscr();
printf("Enter two no");
scanf("%d %d",&a,&b);
printf("Swapping using temporary variable\n");
temp=a;
a=b;
b=temp;
printf("A=%d\t%d",a,b);
printf("\nSwapping with Addition and Substraction\n");
a=a+b;
b=a-b;
a=a-b;
printf("A=%d\tB=%d",a,b);
printf("\n Swapping using XOR bitwise operator\n");
a=a^b;
b=a^b;
a=a^b;
printf("A=%d\tB=%d",a,b);
getch();
        return 0;
}

Output:


Enjoy :)


0 comments:

Post a Comment

 

Pro

About