Recursive fibonacci function. : Recursive « Subroutine « Perl






Recursive fibonacci function.

   

@sampleValues = (0, 1, 2, 3, 4, 5, 6, 10, 20, 30, 35);

foreach ( @sampleValues ) {
   print "fibonacci( $_ ) = ", fibonacci( $_ ), "\n";
}

sub fibonacci
{
   my $number = shift;  # get the first argument

   if ( $number == 0 or $number == 1 ) { # base case
      return $number;
   } 

   else {                                # recursive step
      return fibonacci( $number - 1 ) + fibonacci( $number - 2 );
   }
}

   
    
    
  








Related examples in the same category

1.Recursive factorial subroutine
2.Recursive subroutine
3.Write recursive subroutines
4.calculate 1000th element of standard Fibonacci sequence
5.factorial with recursive function
6.A recursive subroutine to perform arithmetic.