## 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

``` 1  #include <stdio.h>
2  int main (int argc, char *argv[])
3  {
4    int A = 1, B = 2;
5    printf ("A = %d, B = %d\n");
6    printf ("Exchanging A <> B\n");
7    A = (A + B);
8    B = A - B; /* equal to (A + B) - B == A */
9    A = A - B; /* equal to (A + B) - B (Value of A) == B */
10    printf ("A = %d, B = %d\n");
11    return (0);
12  }```

## Output

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

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

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

0

Similar topics related to this section