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
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.