PL/SQL Program to Swap two Numbers
Here you will know two different method of PL/SQL program to swap two numbers using a temporary variable and without using a temporary variable.
PL/SQL Program to Swap two Numbers using temporary variable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | DECLARE num1 NUMBER; num2 NUMBER; temp NUMBER; BEGIN DBMS_OUTPUT.PUT_LINE('Enter the first number:'); num1 := &num1; DBMS_OUTPUT.PUT_LINE('Enter the second number:'); num2 := &num2; -- Print numbers before swapping DBMS_OUTPUT.PUT_LINE('Before Swapping:'); DBMS_OUTPUT.PUT_LINE('num1 = ' || num1 || ' and num2 = ' || num2); -- Swap the numbers using temp variable temp := num1; num1 := num2; num2 := temp; -- Print numbers after swapping DBMS_OUTPUT.PUT_LINE('After Swapping:'); DBMS_OUTPUT.PUT_LINE('num1 = ' || num1 || ' and num2 = ' || num2); END; / |
Output
Enter the first number:22
Enter the second number:12
Before Swapping:
num1 = 22 and num2 = 12
After Swapping:
num1 = 12 and num2 = 22
PL/SQL Program to Swap two Numbers without using temporary variable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | DECLARE num1 NUMBER; num2 NUMBER; BEGIN DBMS_OUTPUT.PUT_LINE('Enter the first number:'); num1 := &num1; DBMS_OUTPUT.PUT_LINE('Enter the second number:'); num2 := &num2; -- Print numbers before swapping DBMS_OUTPUT.PUT_LINE('Before Swapping:'); DBMS_OUTPUT.PUT_LINE('num1 = ' || num1 || ' and num2 = ' || num2); -- Swap the numbers without using temp variable num1 := num1 + num2; num2 := num1 - num2; num1 := num1 - num2; -- Print numbers after swapping DBMS_OUTPUT.PUT_LINE('After Swapping:'); DBMS_OUTPUT.PUT_LINE('num1 = ' || num1 || ' and num2 = ' || num2); END; / |
Output
Enter the first number:22
Enter the second number:12
Before Swapping:
num1 = 22 and num2 = 12
After Swapping:
num1 = 12 and num2 = 22
Check out our other PL/SQL programs examples