Swapping any two numbers is an indispensable task in many sorting algorithm. So it becomes very important to swap numbers, using different algorithms so that we can fit the algorithm according to the hours need.
I have used the following four algorithm for swapping the numbers:-
- Swapping two numbers using a third variable.
- Swapping two numbers without using a third variable.
- Swapping using a function.
- Swapping numbers using bitwise XOR operator. (This is the most interesting one.)
SWAP TWO NUMBERS USING A THIRD VARIABLE
/******************************************************************************/
//SWAP TWO NUMBERS USING A THIRD VARIABLE
#include<stdio.h>
#include<conio.h>
int main(){
int a,b,tmp;
clrscr();
printf("ENTER THE VALUE OF A AND B : \n");
printf("ENTER A : ");
scanf("%d",&a);
printf("ENTER B : ");
scanf("%d",&b);
tmp=a;
a=b;
b=tmp;
printf("A = %d \nB = %d",a,b);
getch();
}
/*******************************************************************************/
SWAP TWO NUMBERS WITHOUT USING THE THIRD VARIABLE
/*********************************************************************************/
//SWAP TWO NUMBERS WITHOUT USING THE THIRD VARIABLE
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("ENTER THE VALUE OF A AND B :
\n");printf("ENTER A : ");
scanf("%d",&a);
printf("ENTER B : ");
scanf("%d",&b);
a=a+b;
b=a-b;
a=a-b;
printf("A = %d \nB = %d",a,b);
getch();
}
/*********************************************************************************/
SWAPPING USING A FUNCTION
In this method, I have passed the address of the variables, that we need to swap, instead of simply passing the variable.
In case if we simply pass variables by call by value mechanism, then only the local variables in the swapping function will be swapped, and no effect will be seen in the respective values of variables in the main function.
/**********************************************************************************/
//SWAPPING USING A FUNCTION CALL
#include<stdio.h>
#include<conio.h>
void swap(int*,int*);
void main()
{
int a,b;
clrscr();
printf("ENTER THE VALUE OF A AND B : \n");
printf("ENTER A : ");
scanf("%d",&a);
printf("ENTER B : ");
scanf("%d",&b);
swap(&a,&b);
printf("A = %d \nB = %d",a,b);
getch();
}
void swap(int *p1,int*p2)
{
int tmp;
tmp=*p1;
*p1=*p2;
*p2=tmp;
}
/*********************************************************************************/
SWAPPING NUMBERS USING BITWISE XOR OPERATOR
/**********************************************************************************/
//SWAPPING NUMBERS USING BITWISE XOR OPERATOR
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("ENTER THE VALUE OF A AND B : \n");
printf("ENTER A : ");
scanf("%d",&a);
printf("ENTER B : ");
scanf("%d",&b);
a=a^b;
b=a^b;
a=a^b;
printf("A = %d \nB = %d",a,b);
getch();
}
/********************************************************************************/
No comments:
Post a Comment