If you want to swap two variables, you would normally require a temporary third variable. But how to swap them without using a third variable? This is quite often a popular interview question for programming jobs.
Below is a sample code written in C to swap two numbers without any temporary variables. Integer arithmetic is used for the operation.
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int x, y; char *end; if(argc!=3) { printf("\nUsage: %s <x> <y>\n",argv[0]); exit(0); } x = strtol(argv[1],&end,10); if (argv[1] == end) { printf ("\nx is invalid!"); exit(1); } y = strtol(argv[2],&end,10); if (argv[2] == end) { printf ("\ny is invalid!"); exit(2); } printf("\nbefore-swap: x=%-10d y=%-10d",x,y); // let x = sum of both x and y x=x+y; // y = x-y // substitute x=x+y // y = (x+y)-y // y = x+y-y // y = x y=x-y; // y now has the value of x and x is the sum of the 2 numbers // x = (x+y)-y // x = x+y-y // x = x x=x-y; printf("\nafter-swap : x=%-10d y=%-10d",x,y); return 0; }
The actual swapping of the variables is done by the three lines highlighted above. The comments above the three lines provide the reasons behind the arithmetic steps.