Q:

Fibonacci Series in Php

0

Fibonacci series is the one in which you will get your next term by adding previous two numbers.

For example,

 

0 1 1 2 3 5 8 13 21 34  

Here, 0 + 1 = 1  

            1 + 1 = 2  

            3 + 2 = 5  

and so on.


Logic:

  • Initializing first and second number as 0 and 1.
  • Print first and second number.
  • From next number, start your loop. So third number will be the sum of the first two numbers.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Example:

We'll show an example to print the first 12 numbers of a Fibonacci series.

<?php  
$num = 0;  
$n1 = 0;  
$n2 = 1;  
echo "<h3>Fibonacci series for first 12 numbers: </h3>";  
echo "\n";  
echo $n1.' '.$n2.' ';  
while ($num < 10 )  
{  
    $n3 = $n2 + $n1;  
    echo $n3.' ';  
    $n1 = $n2;  
    $n2 = $n3;  
    $num = $num + 1;  
?>  

Output:

 

Fibonacci series using Recursive function

Recursion is a phenomenon in which the recursion function calls itself until the base condition is reached.

<?php  
/* Print fiboancci series upto 12 elements. */  
$num = 12;  
echo "<h3>Fibonacci series using recursive function:</h3>";  
echo "\n";  
/* Recursive function for fibonacci series. */  
function series($num){  
    if($num == 0){  
    return 0;  
    }else if( $num == 1){  
return 1;  
}  else {  
return (series($num-1) + series($num-2));  
}   
}  
/* Call Function. */  
for ($i = 0; $i < $num; $i++){  
echo series($i);  
echo "\n";  
}  

Output:

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now