your image

PHP Fibonacci Series Program - javatpoint

javapoint
Related Topic
:- PHP Java information technology

Fibonacci Series

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

For example,

  1. 0 1 1 2 3 5 8 13 21 34  
  2. Here, 0 + 1 = 1  
  3.             1 + 1 = 2  
  4.             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.

Example:

 

HTML Tutorial

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

  1. <?php  
  2. $num = 0;  
  3. $n1 = 0;  
  4. $n2 = 1;  
  5. echo "<h3>Fibonacci series for first 12 numbers: </h3>";  
  6. echo "\n";  
  7. echo $n1.' '.$n2.' ';  
  8. while ($num < 10 )  
  9. {  
  10.     $n3 = $n2 + $n1;  
  11.     echo $n3.' ';  
  12.     $n1 = $n2;  
  13.     $n2 = $n3;  
  14.     $num = $num + 1;  
  15. ?>  

Output:

Fibonacci series using Recursive function

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

  1. <?php  
  2. /* Print fiboancci series upto 12 elements. */  
  3. $num = 12;  
  4. echo "<h3>Fibonacci series using recursive function:</h3>";  
  5. echo "\n";  
  6. /* Recursive function for fibonacci series. */  
  7. function series($num){  
  8.     if($num == 0){  
  9.     return 0;  
  10.     }else if( $num == 1){  
  11. return 1;  
  12. }  else {  
  13. return (series($num-1) + series($num-2));  
  14. }   
  15. }  
  16. /* Call Function. */  
  17. for ($i = 0; $i < $num; $i++){  
  18. echo series($i);  
  19. echo "\n";  
  20. }  

Output:

Comments