1,105,340 Community Members

Fibonacci sequence

Member Avatar
Angel78
Newbie Poster
20 posts since May 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Been trying this for a while and even searched the net but didn't get what I am doing wrong, I got the function but it's just that it won't print the two first digits that is supposed to be 0 and 1 followed by what's get printed by my code.

<?php
//Create a function
function fibonacci($nr){
    //Make an array to hold the numbers
    $prev = array(0, 1);
    //Make the loop
    for ($i = 0; $i < $nr; $i++){
        //Number is the sum of the previous two
        $num = $prev[0]+ $prev[1];
        //Echo out the number
        echo $num . '<br>';
        //The sum of the two numbers is put in the second array
        $prev[0] = $prev[1];
        //The second array holds the new value
        $prev[1] = $num;
    }
}
//Enter how many numbers you would like to generate
fibonacci(15);
?>

The two starting numbers is there in the array (0, 1), what am I missing?

Member Avatar
drjohn
Posting Pro
526 posts since Mar 2010
Reputation Points: 50 [?]
Q&As Helped to Solve: 106 [?]
Skill Endorsements: 4 [?]
 
1
 

Your first step, outside the loop, should be to print the the first two numbers that you are seeding the array with
echo $prev[0];
echo $prev[1];
then continue up to your target value in the loop.
but loop like htis
for ($i = 2; $i < $nr; $i++)
or you will go two steps past the limit the users asked for.
Simples.

Member Avatar
zeroliken
Nearly a Posting Virtuoso
1,222 posts since Nov 2011
Reputation Points: 79 [?]
Q&As Helped to Solve: 216 [?]
Skill Endorsements: 15 [?]
 
0
 

how about printing those first two numbers before entering the loop since they're static output for all fibonacci cases

Member Avatar
Angel78
Newbie Poster
20 posts since May 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Yeah I just thought about this, I got 0 and 1, 0+1=1 and so on so obviously it won't print the first 0 then 1.

Your right, I should just echo them out, thanks.

Question Answered as of 1 Year Ago by drjohn and zeroliken
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: