swap() without any extra variable in C
Suppose x = 10, y = 8
x = x + y ( 10 + 8 = 18 )
y = x - y ( 18 - 8 = 10 )
x = x - y ( 18 - 10 = 8 )
Now x = 8, y = 10
In Code :
This is correct for any value.
x = x + y ( 10 + 8 = 18 )
y = x - y ( 18 - 8 = 10 )
x = x - y ( 18 - 10 = 8 )
Now x = 8, y = 10
In Code :
- // call by reference
- #include <stdio.h>
- int a, b;
- void swap1(void)
- {
- int tmp = b;
- b = a;
- a = tmp;
- }
- void swap2(void)
- {
- a ^= b;
- b ^= a;
- a ^= b;
- }
- void swap3(void)
- {
- a = a + b;
- b = a - b;
- a = a - b;
- }
- int main(void)
- {
- scanf("%d%d",&a,&b);
- printf("%d%d\n",a,b);
- swap1();
- printf("%d%d\n",a,b);
- swap2();
- printf("%d%d\n",a,b);
- swap3();
- printf("%d%d\n",a,b);
- }
This is correct for any value.
No comments