top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Swap value two variables without using third variable or +/- operator?

+2 votes
868 views

How can I wwap value two variables without using third variable or +/- operator?

posted Jul 4, 2014 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

3 Answers

+2 votes

We can use the XOR.

x = x XOR y
y = x XOR y
x = x XOR y

answer Jul 4, 2014 by Prakash Singh
0 votes

Use bitwise XOR somethign like

 int x = 1, y = 2;

  x = x ^ y;  // x now becomes 3(0011)
  y = x ^ y;  // y becomes 2 (0010)
  x = x ^ y;  // x becomes 1 (0001)

Or use * and / operation

int x = 1, y = 20;

x = x * y;  // x now becomes 20
y = x / y;  // y becomes 1
x = x / y;  // x becomes 20
answer Jul 4, 2014 by Salil Agrawal
In case of 0 and other value your logic will fail dear
0 votes
#include <stdio.h>
void swap(int *xp, int *yp)
{
    *xp = *xp ^ *yp;
    *yp = *xp ^ *yp;
    *xp = *xp ^ *yp;
}

int main()
{
  int x = 10, y = 5;
  swap(&x, &y);
  printf("After swap(&x, &y): x = %d, y=%d", x, y);
  return 0;
}
answer Mar 10, 2016 by Ashish Kumar Khanna
Similar Questions
0 votes

a and b are compared against
the threshold ‘TH’, and the nearest value is voted as output

0 votes

I have a recursive function as below,

void func()
{
       if(counter>10)
              return;
       func();
}

Here, I need to come out of the function when counter reaches specific number(10 as per example).
Now, the condition is, I can't take this counter as global or static or can't pass this counter as parameter.

Any suggestion to solve this given above terms.

...