Write a PL/SQL code to get the Fibonacci Sequence.
First, I will explain what is Fibonacci Sequence and how to get this series.
So, Fibonacci Sequence is a series of numbers 0,1,1,2,3,5,8,13,21.............
In Fibonacci Sequence, first and second elements are 0 and 1 and to get the next elements we will add the previous elements and it will generate the next element.
So, first element=0
second element =1
third element=sum of last 2 elements (first element + second element)
=0+1
=1
fourth element=second element + third element
=1+1
=2
fifth element=third element + fourth element
=1+2
=3
So in this way we can generate a Fibonacci Sequence.
Program Code:
SQL> declare
2 a number(5);
3 b number(5);
4 c number(5);
5 n number(5);
6 i number(5);
7 begin
8 n:=6;
9 a:=0;
10 b:=1;
11 for i in 1..n
12 loop
13 c:=a+b;
14 a:=b;
15 b:=c;
16 dbms_output.put_line(c);
17 end loop;
18 end;
19 /
Thanks.
First, I will explain what is Fibonacci Sequence and how to get this series.
So, Fibonacci Sequence is a series of numbers 0,1,1,2,3,5,8,13,21.............
In Fibonacci Sequence, first and second elements are 0 and 1 and to get the next elements we will add the previous elements and it will generate the next element.
So, first element=0
second element =1
third element=sum of last 2 elements (first element + second element)
=0+1
=1
fourth element=second element + third element
=1+1
=2
fifth element=third element + fourth element
=1+2
=3
So in this way we can generate a Fibonacci Sequence.
Program Code:
SQL> declare
2 a number(5);
3 b number(5);
4 c number(5);
5 n number(5);
6 i number(5);
7 begin
8 n:=6;
9 a:=0;
10 b:=1;
11 for i in 1..n
12 loop
13 c:=a+b;
14 a:=b;
15 b:=c;
16 dbms_output.put_line(c);
17 end loop;
18 end;
19 /
Thanks.
No comments:
Post a Comment