Exchange two variable without third variable

This looks very tricky but not very hard to think a logic for this. Let say we have two variables A and B. Now we can add them and store in A. At this point A contains value of A plus B i.e. A = A + B. Now say subtract B from it (A - B). We can get value of A and store it in B i.e. B = A - B. Now B contains value of A. We are almost half done. Now subtract B from it which is actually contains value of A to get the value of B in A i.e. A = A - B. We are done exchange these two. Let construct a C program.

Source Code

#include <stdio.h>
int main (int argc, char *argv[])
{
  int A = 1, B = 2;
  printf ("A = %d, B = %d\n");
  printf ("Exchanging A <> B\n");
  A = (A + B);
  B = A - B; /* equal to (A + B) - B == A */
  A = A - B; /* equal to (A + B) - B (Value of A) == B */
  printf ("A = %d, B = %d\n");
  return (0);
}

Output

A = 2, B = 1
Exchanging A <> B
A = 1, B = 2

A = -2, B = -1
Exchanging A <> B
A = -1, B = -2

About our authors: Team EQA

You have viewed 1 page out of 252. Your C learning is 0.00% complete. Login to check your learning progress.

#