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
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
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
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
#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