We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,931 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Fibonacci sequence

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?

2
Contributors
3
Replies
47 Minutes
Discussion Span
2 Months Ago
Last Updated
19
Views
Question
Answered
Angel78
Newbie Poster
20 posts since May 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

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.

drjohn
Posting Pro
508 posts since Mar 2010
Reputation Points: 76
Solved Threads: 99
Skill Endorsements: 4

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

zeroliken
Nearly a Posting Virtuoso
1,346 posts since Nov 2011
Reputation Points: 214
Solved Threads: 205
Skill Endorsements: 14

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.

Angel78
Newbie Poster
20 posts since May 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0
Question Answered as of 2 Months Ago by drjohn and zeroliken

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0769 seconds using 2.7MB