PHP program to print fibonacci series.
The below program prints a Fibonacci Series without recursion and with recursion. The PHP echo statement is used to output the result on the screen. A series is called as a Fibonacci series if the each next term of the series is a sum of previous two numbers.
Fibonacci Series:
a, b, c, d, e
c = a+b
d = b+c
e = c+d
For example,
0 2 2 4 6 10 16 26
Without using recursion:
Example
<!DOCTYPE html> <html> <body> <?php $n = 0; $a = 0; $b = 2; echo "Fibonacci series with the first 2 numbers as 0 and 2 is: "; echo "$a, $b"; while ($n < 26 ) { $c = $b + $a; echo ", "; echo "$c"; $a = $b; $b = $c; $n = $n + 1; } ?> </body> </html> |
Output
Fibonacci series with the first 2 numbers as 0 and 2 is: 0, 2, 2, 4, 6, 10, 16, 26, 42, 68, 110, 178, 288, 466, 754, 1220, 1974, 3194, 5168, 8362, 13530, 21892, 35422, 57314, 92736, 150050, 242786, 392836 |
Using recursion:
Example
<!DOCTYPE html> <html> <body> <?php function fibonacci($x,$y) { $c = $x + $y; return $c; } $a = 0; $b = 2; echo "Fibonacci series with the first 2 numbers as 0 and 2 is: "; echo "$a, $b"; for ($i = 0; $i < 26; $i++) { echo ", "; echo fibonacci($a,$b); $z = fibonacci($a,$b); $a = $b; $b = $z; } ?> </body> </html> |
Output
Fibonacci series with the first 2 numbers as 0 and 2 is: 0, 2, 2, 4, 6, 10, 16, 26, 42, 68, 110, 178, 288, 466, 754, 1220, 1974, 3194, 5168, 8362, 13530, 21892, 35422, 57314, 92736, 150050, 242786, 392836 |
Please Share