Variables Notes
BCA NOTES
Question –How to exchange the value of two variables without using a third.
Answer –
Any student of Variables programming – Basic could recognize the following code:
aux = x;
x = y;
y = aux;
It’s about the classic exchange of variable.
However, there are other forms of exchange the value of two variable; forms that do not require use another auxiliary.
Here I will expose two that I know, the first one using basic arithmetic and the second using Bool algebra.
Using basic arithmetic
The code is the following:
x = x + y;
y = x – y;
x = x – y;
This code is very interesting,
However, it is possible that, if the sum of “x” and “y” gave a very high value, we cause an overflow in the variable “x” and everything goes wrong.
Using Bool algebra.
Maybe the language programmers Assemblers are familiar with this form.
It is about using the “XOR” binary operation (or excluding).
a ^ = b;
b ^ = a;
a ^ = b;
Alternatively it can be done in a line:
a ^ = b ^ = a ^ = b;
This code is glory. Although as I understand it is not portable, so no use it!
Any student of programming Basic could recognize the following code:
aux = x;
x = y;
y = aux;
It’s about the classic exchange of variable.
However, there are other forms of exchange the value of two variables; forms that do not require use another auxiliary.
Here I will expose two that I know, the first one using basic arithmetic and the second using Bool algebra.
Using basic arithmetic
The code is the following:
x = x + y;
y = x – y;
x = x – y;
This code is very interesting, However, it is possible that, if the sum of “x” and “y” gave a very high value, we cause an overflow in the variable “x” and everything goes wrong.
Using Bool algebra.
Maybe the language programmers Assemblers are familiar with this form.
It is about using the “XOR” binary operation (or excluding).
a ^ = b;
b ^ = a;
a ^ = b;
Alternatively it can be done in a line:
a ^ = b ^ = a ^ = b;
This code is glory. Although as I understand it is not portable, so no use it!
4 Responses
[…] Previous story How to exchange the value of two variables without using a third. […]
[…] C Programming – Write a program in assembly language to check whether says: […] Previous story How to exchange the value of two variables… […]
[…] Variables Notes […]
[…] Variables Notes […]