pl/sql program to swap two numbers

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:

  1. DECLARE: This keyword indicates the start of the declaration section where we define variables.
  2. num1 NUMBER;: This line declares a variable named num1 of the NUMBER data type, which will store the first number.
  3. num2 NUMBER;: This line declares a variable named num2 of the NUMBER data type, which will store the second number.
  4. temp NUMBER;: This line declares a variable named temp of the NUMBER data type, which will be used to temporarily hold a value during swapping.
  5. BEGIN: This keyword signifies the beginning of the executable section.
  6. num1 := &num1;: This line prompts the user to enter the first number and assigns the input value to the num1 variable. The & symbol is used to retrieve the value entered by the user.
  7. num2 := &num2;: This line prompts the user to enter the second number and assigns the input value to the num2 variable.
  8. DBMS_OUTPUT.PUT_LINE('Before swapping:');: This line uses the DBMS_OUTPUT.PUT_LINE procedure to display a message indicating the numbers before swapping.
  9. DBMS_OUTPUT.PUT_LINE('Number 1: ' || num1);: This line displays the value of num1 before swapping.
  10. DBMS_OUTPUT.PUT_LINE('Number 2: ' || num2);: This line displays the value of num2 before swapping.
  11. temp := num1;: This line stores the value of num1 in the temp variable.
  12. num1 := num2;: This line assigns the value of num2 to num1, effectively swapping the values.
  13. num2 := temp;: This line assigns the value stored in temp (which was the original value of num1) to num2, completing the swap.
  14. DBMS_OUTPUT.PUT_LINE('After swapping:');: This line displays a message indicating the numbers after swapping.
  15. DBMS_OUTPUT.PUT_LINE('Number 1: ' || num1);: This line displays the value of num1 after swapping.
  16. DBMS_OUTPUT.PUT_LINE('Number 2: ' || num2);: This line displays the value of num2 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.