Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Factorial of a number in pl/sql (Not showing the correct output)

I have written down a code in pl/sql but output is not showing
having trouble with this code.

declare

num number(20):= 0;
val number(10):= 5;
temp number(10):= 0;

function factorial (n1 in number)
return number
is
fact number(10):= 1;

begin
temp:= n1;
loop
  if fact <=0 then
     exit;
  else
     fact := fact *temp;
     temp:=temp-1;
  end if;
end loop;
return fact;
end;

begin
num:= factorial(val);
dbms_output.put_line('Factorial of ' ||val||' is '||num);
end;

Output:- Factorial of 5 is 0

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The line:

if fact <=0 then

should be:

if temp <=0 then

You don’t really need the ‘else’ part, because the ‘if’ exits the loop anyway; so you could do:

loop
  if temp <=0 then
     exit;
  end if;
  fact := fact *temp;
  temp:=temp-1;
end loop;

Or avoid the explicit check by using a while loop:

while temp > 0 loop
  fact := fact *temp;
  temp:=temp-1;
end loop;

… etc.

db<>fiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading