As we all know that we can send any number of arguments to a subroutine in Perl. Would the following example be a correct demonstration of recursion to display fibonacci series (5 values)?
#!/usr/bin/perl -w
use strict;
sub recursion
{
if ($_[0] && $_[2])
{
print $_[2],"\n";
if ($_[0] < 5)
{
return recursion($_[0] + 1, $_[2], $_[1] + $_[2]);
}
else
{
return $_[0];
}
}
elsif ($_[0] && !$_[1] && !$_[2])
{
print "0\n";
return recursion($_[0], 0, 1);
}
}
print "\nFibo Series : \n";
recursion(1);
print "\nEnter to exit";
<>;
I know it is a lame example… but my aim is to know whether this type of implementation would still qualify to be an example for recursion?
Hoping for no brickbats :)
Edit:
depending upon some condition, if the program decides to send only one argument or two or multiple arguments to itself… would that be a valid characteristic?
A function is recursive if it calls itself. Your recursion
function calls itself, so it's recursive. codaddict's conditions are necessary for a recursive function to work properly, but a function could still be recursive if they weren't met. (It would just be recursive and buggy.)
Yes. Its a recursive function. It meets the required conditions of
$_[0]
becomes 5
$_[0] + 1
to recursive calls.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With