Fibonacci Sequence – Part 2

In Fibonacci Sequence – Part 1, we saw how to calculate the nth term.
But what if we want to generate about n terms?
Yes. Let us move on to Arrays.

function fib(n)
{

   if(n == 1) return [0];
   if(n == 2) return [0, 1];
   var nterms = [0, 1];
   for(var i = 3; i <= n; ++i)
       nterms[nterms.length]
            = nterms[nterms.length - 2] + nterms[nterms.length - 1];
   return nterms;
}

alert(fib(10));

In the above code, we can see that both the array variable nterms and scalar variable i are declared with the same keyword var.
And you can see that we haven’t specified the size for the array.
(This is not the case with other languages like Java or VB.NET).
The size can be extended to any number during runtime.
(Here, we are doing it in the for loop).
This is the power of scripting languages.

sub fib {
   my $n = pop @_;
   return (0)    if $n == 1;
   return (0, 1) if $n == 2;
   my @nterms = (0, 1);
   $nterms[@nterms + 0]
      = $nterms[@nterms - 2] + $nterms[@nterms - 1]
         for 3 .. $n;
   @nterms;
}
my @result = fib(10);
print "@result\n";

In JavaScript, both the literal arrays and array indexing are done by “[” and “]”.
In Perl, there is no literal arrays. Instead it is called as List.
So, to denote List, we use “(” and “)” and to index the arrays we use “[” and “]”.
Here also, the array size is increased dynamically.

As mentioned in the previous post, the if and for (of Perl version) are called statement modifiers.
In Line No. 9, the keyword return is not used.
In Perl, the last evaluated expression is returned, by default.
Here we are returning the array variable nterms.
As a good practice, we should use the keyword to let others know that we are returning intentionally.

The recursive version using arrays would look more interesting.
Let us see it in Fibonacci Sequence – Part 3

Advertisements