Skip to main content

program to different ways to swap values of two variables without using temporary variables

shiv@ubuntu:~/ds/list$ cat swap.c

/*
 * Program to swap values of two variables
 * without using temporary variables
 */

#include <stdio.h>

/*
 * swaping values two variables using arithmetic
 * operators
 */

void swap(int *x, int *y)
{
  *x = *x + *y;
  *y = *x - *y;
  *x = *x - *y;
}

/*
 * swaping values of variables using
 * XOR oprations
 */

void swap_xor(int *x, int *y)
{
  *x = *x ^ *y;
  *y = *x ^ *y;
  *x = *x ^ *y;

}

int main()
{
 int x, y, a, b;

 x=20;
 y=30;
 swap(&x, &y);
 printf("\nafter swap x=%d and y=%d", x, y);

 a=50;
 b=100;
 swap_xor(&a, &b);
 printf("\nafter swap a=%d and b=%d\n", a, b);

}

Comments