Saturday, 13 September 2014

Swap two numbers without using temporary variable

1st method(using arithmetic operators) :-

#include <stdio.h>
int main()
{
  int x = 10, y = 5;
  x = x + y;  // x is now 15
  y = x - y;  // y is 10
  x = x - y;  // and swapped, x is 5
 printf("swapped values :- x is %d, y is %d", x, y);
   
 return 0;
}

2nd method(using Bitwise XOR) :-

#include <stdio.h>
int main()
{
  int x = 10, y = 5;
  x = x ^ y;  // x is now 15(1111)
  y = y ^ x;  // y is 10(1010)
  x = x ^ y;  // and swapped, x is 5(0101)

  printf("swapped values :- x is %d, y is %d", x, y);
  return 0;
}

No comments:

Post a Comment