0

I've to create a function which print the Fibonacci series as its result. I've used a varray in the program below but it is giving me an error saying "PLS-00201: identifier 'ARRAY' must be declared" on line no. 2.

create function fibonacci7(x int)
return VARRAY
is
type fib IS VARRAY(25) OF VARCHAR(10);
a number(3):=1;
b number(3):=1;
c number(3);
i number(3):=1;
begin
while a<=n
    loop
       fib(i) := a;
       c:=a+b;
       a:=b;
       b:=c;
       i:=i+1;
    end loop;
return codes_;
end ;
/

select fibonacci7(5) from dual;

1 Answers1

0

I think this will do what you want. VARRAY's have a little different syntax than what you were using.

set serveroutput on size 1000000

create or replace type fibtype AS VARRAY(25) OF NUMBER;
/

create or replace function fibonacci7(n number)
return fibtype
is
fib fibtype := fibtype();
a number:=1;
b number:=1;
c number;
i number:=1;
begin
fib.extend(n);
while i<=n
    loop
       fib(i) := a;
       c:=a+b;
       a:=b;
       b:=c;
       i:=i+1;
    end loop;
return fib;
end ;
/

declare
i number;
fib fibtype := fibtype();
begin
fib := fibonacci7(6);
for i in 1..fib.count loop
  dbms_output.put_line(to_char(fib(i)));
end loop;
end;
/

Here is the output.

1
1
2
3
5
8

Bobby

p.s. Fixed to work with fib(6) and made array numbers

Bobby Durrett
  • 1,223
  • 12
  • 19
  • 1
    I believe there is a slight error in the function. If the function call fibonacci7(n) means `get the first n values in the Fibonacci sequence` then statement *while a<=n* should be *while i<=n*. At current the routine exits the value that point in greater then the specified number (n), not at the nth number. The function works for 5 since Fib(5)=5, but fails for Fib(6)=8. The output values from the anonymous block for Fib(6) are 1,1,2,3,5,null. – Belayer May 03 '21 at 02:32