EmbLogic's Blog

Different methods of swapping 2 numbers

#include<stdio.h>
void swap(int *,int *);

int main()
{
int temp;
int *t;
int a=100,b=200;
//Using 3 variables
//1.1
temp = a;
a = b;
b = temp;
printf(“%d %d\n”,a,b);
//1.2
swap(&a,&b);
printf(“%d %d\n”,a,b);

//Using 2 variables
//2.1
a += b;
b = a-b;
a = a-b;
printf(“%d %d\n”,a,b);
//2.2
if(a!=0 && b!=0)
{
a *= b;
b = a/b;
a = a/b;
printf(“%d %d\n”,a,b);
}
//2.3
a = a^b;
b = a^b;
a = a^b;
printf(“%d %d\n”,a,b);
//Using 2 variables in single step
//3.1
a = b+a-(b=a);
printf(“%d %d\n”,a,b);
//3.2
a = b*a/(b=a);
printf(“%d %d\n”,a,b);
//3.3
a ^=b^=a^=b;
printf(“%d %d\n”,a,b);
return 0;
}
void swap(int *x,int *y)
{
int tmp;
tmp = *x;
*x = *y;
*y = tmp;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

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