Monday, August 20, 2007

Interesting C Program -16

Can u write a C program to swap two integers that does not use a temporary variable (or that uses only two variables to be swapped)?


Here goes an implementation:


#include "stdio.h"
int main()
{
int a=1,b=3;
printf("BEFORE SWAPPING : a=%d & b=%d\n",a,b);
a^=b^=a^=b;
printf("AFTER SWAPPING : a=%d & b=%d\n",a,b);
}


The output looks something like this:

BEFORE SWAPPING : a=1 & b = 3
AFTER SWAPPING : a=3 & b = 1

Looks good isn't it?

No comments:

Search Google

Books that I refer to...

  • The Complete Reference C, Fourth Edition
  • The C Programming Language