PL/SQL Program to Swap two Numbers

PL/SQL Program to Swap two Numbers :-


We are going to write a PL/SQL program to swap variable with or without using temporary variable.

Method 1: PL/SQL Program to Swap two Numbers Using Temporary Variable

declare
    num1 number;
    num2 number;
    temp number;
 
begin
    num1:=5;
    num2:=10;
    
    dbms_output.put_line('number before swapping:');
    dbms_output.put_line('num1='||num1||' num2='||num2);
    
    temp:=num1;
    num1:=num2;
    num2:=temp;
    
    dbms_output.put_line('after swapping:');
    dbms_output.put_line('num1='||num1||' num2='||num2);
    
end;
/

Output:-

Numbers before swapping:
num1=10 num2=20
numbers after swapping:
num1=20 num2=10

Method 2: PL/SQL Program to Swap two Numbers Without Using Temporary Variable


declare
    num1 number;
    num2 number;
 
begin
    num1:=5;
    num2:=10;
    
    dbms_output.put_line('Numbers before swapping:');
    dbms_output.put_line('num1='||num1||' num2='||num2);
    
    num1:=num1+num2;
    num2:=num1-num2;
    num1:=num1-num2;
    
    dbms_output.put_line('numbers after swapping:');
    dbms_output.put_line('num1='||num1||' num2='||num2);
    
end;
/

 

https://bit.ly/2lgLuJ1 https://bit.ly/2lAbgYW https://bit.ly/2ngU8ry

Leave a Reply

Your email address will not be published. Required fields are marked *