PL/SQL Program to Calculate Factorial

PL/SQL Program to Calculate Factorial

  • PLSQL
  • 2 mins read

Here is an example of a PL/SQL program to calculate the factorial of a given number:

PL/SQL Program to Calculate Factorial Example

DECLARE
  num INTEGER := 5;
  factorial INTEGER := 1;

BEGIN
  -- Calculate the factorial of the given number
  FOR i IN 1..num LOOP
    factorial := factorial * i;
  END LOOP;

  -- Print the result
  DBMS_OUTPUT.PUT_LINE('The factorial of ' || num || ' is ' || factorial);
END;

This code calculates the factorial of the number 5, which is 120. The result is then printed to the console using the DBMS_OUTPUT.PUT_LINE function. The output of the program would be:

The factorial of 5 is 120

In this example, the num variable is initialized to 5, and the factorial variable is initialized to 1. The code then uses a FOR loop to iterate over the numbers from 1 to num, and calculates the factorial by multiplying each number by the current value of factorial. This continues until the loop has finished, at which point factorial contains the final result. Finally, the result is printed to the console using the DBMS_OUTPUT.PUT_LINE function.

You can modify the PL/SQL code to calculate the factorial of any number by changing the value of the num variable. You can also use the DBMS_OUTPUT.PUT_LINE function to print intermediate results, or to print the result in a different format.

Related:

  1. PL/SQL Program to Print Employee Details