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