Header Ads Widget

swap two numbers without temp variable

1. Using Addition and Subtraction

#include<stdio.h>
int main()
{
int a,b;
printf("Enter values :");
scanf("%d%d",&a,&b);
printf("Before swapping values :");
printf("a=%d ,b=%d \n",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("After swapping values :");
printf("a=%d ,b=%d \n",a,b);
return 0;

}

Output :
Enter values :4
6
Before swapping values :a=4 ,b=6
After swapping values :a=6 ,b=4

When a and b are too large after addition, the value may go out of integer range.

2. Using Multiplication and Division

#include<stdio.h>
int main()
{
int a,b;
printf("Enter values :");
scanf("%d%d",&a,&b);
printf("Before swapping values :");
printf("a=%d ,b=%d \n",a,b);
a=a * b;
b=a / b;
a=a / b;
printf("After swapping values :");
printf("a=%d ,b=%d \n",a,b);
return 0;

}

Output :
Enter values :4
6
Before swapping values :a=4 ,b=6
After swapping values :a=6 ,b=4

This approach does not work when one of the numbers is  0.
When a and b are too large after multiplication, the value may go out of integer range.

3. Using Bitwise XOR

#include<stdio.h>
int main()
{
int a,b;
printf("Enter values :");
scanf("%d%d",&a,&b);
printf("Before swapping values :");
printf("a=%d ,b=%d \n",a,b);
a=a ^ b;
b=a ^ b;
a=a ^ b;
printf("After swapping values :");
printf("a=%d ,b=%d \n",a,b);
return 0;

}

Output :
Enter values :4
6
Before swapping values :a=4 ,b=6
After swapping values :a=6 ,b=4

Post a Comment

1 Comments