Ans: Numbers of Fibonacci sequence are known as Fibonacci numbers. First few numbers of series are 0, 1, 1, 2, 3, 5, 8 etc, Except first two terms in sequence every other term is the sum of two previous terms, For example 8 = 3 + 5 (addition of 3, 5)
Fibonacci Series using for loop:
<?php $term = 10; $num1 = 0; $num2 = 1; for ($i = 0; $i < $term; $i++) { if ($i <= 1) $result = $i; else { $result = $num1 + $num2; $num1 = $num2; $num2 = $result; } echo "<br>" . $result; } ?>
Fibonacci Series using recursion:
<?php function fibonacci($n) { if ($n == 0) return 0; else if ($n == 1) return 1; else return ( fibonacci($n - 1) + fibonacci($n - 2) ); } $term = 10; for ($i = 1; $i <= $term; $i++) { echo "<br>".fibonacci($c); $c++; } ?>
Output: 0 1 1 2 3 5 8 13 21 34
No comments:
Post a Comment