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.
Now how to generate a Fibonacci Sequence using a program?
Object: Write a PL/SQL code to get the Fibonacci 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.
Now how to generate a Fibonacci Sequence using a program?
- First thing we want to know the length of sequence because its length will be infinite, so we want to know length of sequence to be generated by program. I have taken it as 6
- Second thing we will need first two elements of sequence and for that we will use 2 variables, a=0, b=1
- Now we will need one extra variable which will be the sum of last two elements which in our program is c
- Now we have to use a for loop and just put c=a+b inside that so that the sequence will be generated
Object: Write a PL/SQL code to get the Fibonacci series.
Requirement: Windows XP, Oracle 9i.
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 .
OUTPUT :
SQL>
/
1
2
3
5
8
13
PL/SQL
procedure successfully completed.
RESULT : The
above program in PL/SQL to get the Fibonacci series has been executed
successfully.
So above is a simple program how to generate Fibonacci Sequence. If there is any query regarding anything please comment.
Thanks
So above is a simple program how to generate Fibonacci Sequence. If there is any query regarding anything please comment.
Thanks
0 comments:
Post a Comment