Solution Review: Fibonacci Sequence

In this lesson, we'll look at the explanation of the last challenge.

We'll cover the following

Let’s look at the solution first before jumping into the explanation:

Press + to interact
$range = 6; # change range to print sequence till that point
$ans = "";
$first = 0;
$second = 1;
$fibonacci = 0;
for ($c = 0 ; $c < $range ; $c++ )
{
if ( $c <= 1 ){
$fibonacci = $c;
$ans .= $fibonacci . " ";
}
else{
$fibonacci = $first + $second;
$first = $second;
$second = $fibonacci;
$ans .= $fibonacci . " ";
}
}
$ans =~ s/\s+$//;
print $ans;

Explanation

We have initialized the $range variable up to which we print the sequence. We run the for loop until this $range. In the first two iterations of the loop, we append the “0” and “1” in the if condition, and for every iteration onwards, we find $fibonacci by adding the previous two elements.