Certainly! Here’s a PL/SQL program to swap two numbers:
DECLARE
num1 NUMBER;
num2 NUMBER;
temp NUMBER;
BEGIN
-- Prompt the user for input
num1 := &num1;
num2 := &num2;
-- Display the numbers before swapping
DBMS_OUTPUT.PUT_LINE('Before swapping:');
DBMS_OUTPUT.PUT_LINE('Number 1: ' || num1);
DBMS_OUTPUT.PUT_LINE('Number 2: ' || num2);
-- Swap the numbers
temp := num1;
num1 := num2;
num2 := temp;
-- Display the numbers after swapping
DBMS_OUTPUT.PUT_LINE('After swapping:');
DBMS_OUTPUT.PUT_LINE('Number 1: ' || num1);
DBMS_OUTPUT.PUT_LINE('Number 2: ' || num2);
END;
/
Explanation:
DECLARE
: This keyword indicates the start of the declaration section where we define variables.num1 NUMBER;
: This line declares a variable namednum1
of the NUMBER data type, which will store the first number.num2 NUMBER;
: This line declares a variable namednum2
of the NUMBER data type, which will store the second number.temp NUMBER;
: This line declares a variable namedtemp
of the NUMBER data type, which will be used to temporarily hold a value during swapping.BEGIN
: This keyword signifies the beginning of the executable section.num1 := &num1;
: This line prompts the user to enter the first number and assigns the input value to thenum1
variable. The&
symbol is used to retrieve the value entered by the user.num2 := &num2;
: This line prompts the user to enter the second number and assigns the input value to thenum2
variable.DBMS_OUTPUT.PUT_LINE('Before swapping:');
: This line uses theDBMS_OUTPUT.PUT_LINE
procedure to display a message indicating the numbers before swapping.DBMS_OUTPUT.PUT_LINE('Number 1: ' || num1);
: This line displays the value ofnum1
before swapping.DBMS_OUTPUT.PUT_LINE('Number 2: ' || num2);
: This line displays the value ofnum2
before swapping.temp := num1;
: This line stores the value ofnum1
in thetemp
variable.num1 := num2;
: This line assigns the value ofnum2
tonum1
, effectively swapping the values.num2 := temp;
: This line assigns the value stored intemp
(which was the original value ofnum1
) tonum2
, completing the swap.DBMS_OUTPUT.PUT_LINE('After swapping:');
: This line displays a message indicating the numbers after swapping.DBMS_OUTPUT.PUT_LINE('Number 1: ' || num1);
: This line displays the value ofnum1
after swapping.DBMS_OUTPUT.PUT_LINE('Number 2: ' || num2);
: This line displays the value ofnum2
after swapping.
By running this PL/SQL program, you can easily swap the values of two numbers. The program prompts the user to enter the two numbers, displays them before swapping, performs the swap operation, and then displays the numbers again after the swap. This allows you to verify that the values have indeed been swapped.