You are on page 1of 3

There are so many techniques in which two numbers can be swapped.

This is one of the


fundamental program in C and hence can be addressed in four different ways.
Version 1: Swap two numbers using a temporary variable and using pass by value.
The swapped value from the functions does not return to the calling function, as the variables are
swapped locally within the stack
//Swap two numbers using a temporary variable with pass by value
#include <stdio.h>
#include <time.h>
void swap(int,int);
int main()
{
clock_t begin, end;
int a=10,b=20;
double ts;
begin=clock();
printf("Before Swap a=%d b=%d\n",a,b);
swap(a,b);
printf("After Swap a=%d b=%d\n",a,b);
end =clock();
ts=(double)(end-begin)/CLOCKS_PER_SEC;
printf("The total time taken for execution is %f",ts);
return 0;
}
void swap(int x, int y)
{
int t;
t=x;
x=y;
y=t;
printf("After Swap a=%d b=%d\n",x,y);
}

Version 2: Swap two numbers without using a temporary variable


#include <stdio.h>
#include <time.h>
void swap(int,int);
int main()
{
clock_t begin, end;
int a=10,b=20;
double ts;
begin=clock();
printf("Before Swap a=%d b=%d\n",a,b);
swap(a,b);
end =clock();
ts=(double)(end-begin)/CLOCKS_PER_SEC;

printf("The total time taken for execution is %f\n",ts);


return 0;
}
void swap(int x, int y)
{
x=x+y;
y=x-y;
x=x-y;
printf("After Swap a=%d b=%d\n",x,y);
}

Version 3:

Swap two numbers using pass by reference

#include <stdio.h>
#include <time.h>
void swap(int*,int*);
int main()
{
clock_t begin, end;
int a=10,b=20;
double ts;
begin=clock();
printf("Before Swap a=%d b=%d\n",a,b);
swap(&a,&b);
printf("After Swap a=%d b=%d\n",a,b);
end =clock();
ts=(double)(end-begin)/CLOCKS_PER_SEC;
printf("The total time taken for execution is %f\n",ts);
return 0;
}
void swap(int *x, int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}
Version 4:
Gates.

Swap two numbers using bitwise operators. It is the use of XOR

#include <stdio.h>
#include <time.h>
void swap(int,int);
int main()
{
clock_t begin, end;
int a=10,b=20;
double ts;
begin=clock();

printf("Before Swap a=%d b=%d\n",a,b);


swap(a,b);
end =clock();
ts=(double)(end-begin)/CLOCKS_PER_SEC;
printf("The total time taken for execution is %f\n",ts);
return 0;
}
void swap(int x, int y)
{
x=x^y;
y=x^y;
x=x^y;
printf("After Swap a=%d b=%d\n",x,y);
}

You might also like