Adsense Ad

Tuesday 9 January 2018

Oracle PL/SQL: How to swap two variable number values without using a temporary or third variable?

Given two variables, x and y, swap two variables without using a third variable.
(Using Arithmetic Operators)
The idea is to get sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from sum.
DECLARE
  x NUMBER := 10;
  y NUMBER := 5;
BEGIN 
 -- Code to swap 'x' and 'y'
  x := x + y;  -- x now becomes 15
  y := x - y;  -- y becomes 10
  x := x - y;  -- x becomes 5
  dbms_output.put_line('After Swapping: x = '||x||' , y = '||y);
END;
Output will be: After Swapping: x = 5 , y = 10

Multiplication and division can also be used for swapping.
DECLARE
  x NUMBER := 10;
  y NUMBER := 5;
BEGIN 
 -- Code to swap 'x' and 'y'
  x := x * y;  -- x now becomes 50
  y := x / y;  -- y becomes 10
  x := x / y;  -- x becomes 5
  dbms_output.put_line('After Swapping: x = '||x||' , y = '||y);
END;
Output will be: After Swapping: x = 5 , y = 10

No comments: