PL/SQL Program to find factorial of a number using function
Here you will get pl/sql program to find factorial of a number using function.
PL/SQL Program to find factorial of a number using function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | --function to calculate factorial CREATE OR REPLACE FUNCTION factorial(n IN NUMBER) RETURN NUMBER IS result NUMBER := 1; BEGIN IF n < 0 THEN RETURN NULL; -- Factorial not defined for negative numbers ELSIF n = 0 THEN RETURN 1; -- Factorial of 0 is 1 ELSE FOR i IN 1..n LOOP result := result * i; END LOOP; RETURN result; -- Return result END IF; END; / |
Calling the Function:
1 2 3 4 5 6 7 8 | DECLARE num NUMBER := 5; fact NUMBER; BEGIN fact := factorial(num); -- Call factorial function DBMS_OUTPUT.PUT_LINE('The factorial of ' || num || ' is: ' || fact); END; / |
Output
The factorial of 5 is: 120
Check out our other PL/SQL programs examples