How to swap two numbers without using third variable

Programming

Consider we have two variables x and y containing some number. We are asked to swap the values without using a third variable. To solve this problem we follow the given steps (algorithm)


x = x + y
y = x - y
x = x - y

Swapping two positive numbers


Let x = 10 and y = 20
So,
x = x + y
  = 10 + 20
  = 30

y = x - y
  = 30 - 20
  = 10

x = x - y
  = 30 - 10
  = 20

Swapping a positive and a negative number


Let x = 10 and y = -20
So,
x = x + y
  = 10 + (-20)
  = -10

y = x - y
  = (-10) - (-20)
  = (-10) + 20
  = 10

x = x - y
  = (-10) - 10
  = -20

Swapping two negative numbers


Let x = -10 and y = -20
So,
x = x + y
  = (-10) + (-20)
  = -30

y = x - y
  = (-30) - (-20)
  = (-30) + 20
  = -10

x = x - y
  = (-30) - (-10)
  = (-30) + 10
  = -20

Code in C


#include <stdio.h>

int main(){
	//variables
	int x, y;
	
	//input
	printf("Enter value of x and y: ");
	scanf("%d%d", &x, &y);
	
	//swap
	x = x + y;
	y = x - y;
	x = x - y;
	
	//output
	printf("x = %d y = %d\n", x, y);
	return 0;
}

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT