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 */
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.

 Vote 0

Similar topics related to this section

reverse decimal digits, signed and unsigned compare, palindrome digits, upper and lower 16bit of 32bit unsigned, Exchange variables, prime number, HCF, LCM,

# C Programming Language (Prentice Hall Software)
# Let Us C Paperback - 2006 by Yashavant Kanetkar
# Understanding and Using C Pointers Core techniques for memory management
# Data Structures Using C and C++ Paperback - 1998
# Data Structures In C Paperback - August 11, 2008 by Noel Kalicharan