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 : 

  1. // call by reference
  2. #include <stdio.h>
  3. int a, b;
  4. void swap1(void)
  5. {
  6. int tmp = b;
  7. b = a;
  8. a = tmp;
  9. }
  10. void swap2(void)
  11. {
  12. a ^= b;
  13. b ^= a;
  14. a ^= b;
  15. }
  16. void swap3(void)
  17. {
  18. a = a + b;
  19. b = a - b;
  20. a = a - b;
  21. }
  22. int main(void)
  23. {
  24. scanf("%d%d",&a,&b);
  25. printf("%d%d\n",a,b);
  26. swap1();
  27. printf("%d%d\n",a,b);
  28. swap2();
  29. printf("%d%d\n",a,b);
  30. swap3();
  31. printf("%d%d\n",a,b);
  32. }

This is correct for any value.

No comments

Powered by Blogger.