Open In App

Swap two numbers in PL/SQL without using temp

Last Updated : 05 Jul, 2018
Improve
Improve
Like Article
Like
Save
Share
Report

In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.

Given two numbers num1 and num2 and the task is to swap the value of given numbers.

Examples:

Input : num1  = 1000, num2 = 2000
Output : num1  = 2000, num2 = 1000

Input : num1  = 40, num2 = 20
Output : num1  = 20, num2 = 40

Method 1 (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 
    -- declare variable num1, num2  
    -- of datatype number 
    num1 NUMBER; 
    num2 NUMBER; 
BEGIN 
    num1 := 1000; 
  
    num2 := 2000; 
  
    -- print result before swapping 
    dbms_output.Put_line('Before'); 
  
    dbms_output.Put_line('num1 = ' 
                         || num1 
                         ||' num2 = ' 
                         || num2); 
  
    -- swapping of numbers num1 and num2 
    num1 := num1 + num2; 
  
    num2 := num1 - num2; 
  
    num1 := num1 - num2; 
  
    -- print result after swapping 
    dbms_output.Put_line('After'); 
  
    dbms_output.Put_line('num1 = ' 
                         || num1 
                         ||' num2 = ' 
                         || num2); 
END
-- Program End 


Output:

Before
num1 = 1000 num2 = 2000
After
num1 = 2000 num2 = 1000

Method 2 Multiplication and division can also be used for swapping.




DECLARE 
    -- declare variable num1, num2  
    -- of datatype number 
    num1 NUMBER; 
    num2 NUMBER; 
BEGIN 
    num1 := 1000; 
  
    num2 := 2000; 
  
    -- print result before swapping 
    dbms_output.Put_line('Before'); 
  
    dbms_output.Put_line('num1 = ' 
                         || num1 
                         ||' num2 = ' 
                         || num2); 
  
    -- swapping of numbers num1 and num2 
    num1 := num1 * num2; -- num1 now becomes 15 (1111) 
  
    num2 := num1 / num2; -- num2 becomes 10 (1010) 
  
    num1 := num1 / num2; -- num1 becomes 5 (0101) 
    -- print result after swapping 
    dbms_output.Put_line('After'); 
  
    dbms_output.Put_line('num1 = ' 
                         || num1 
                         ||' num2 = ' 
                         || num2); 
END
  
-- Program End 


Output:

Before
num1 = 1000 num2 = 2000
After
num1 = 2000 num2 = 1000


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads