Fibonacci series is set as a sequence of numbers in which the first two numbers are 0 and 1, depending on the selected beginning point of the sequence, and each subsequent number is the sum of the previous two number. So, in this series, the nth term is the sum of (n-1)th term and (n-2)th term.
Recursion is a method where we repeatedly call the same function until a origin condition is matched to end the recursion.
<?php
// PHP code to get the Fibonacci series
// Get fibonacci series Using Recursive function .
function fibonacciSeries($number){
// if and else if to generate first two numbers
if ($number == 0){
return 0;
}else if ($number == 1){
return 1;
}else{
// Recursive Call to get the upcoming numbers
return (fibonacciSeries($number-1) + fibonacciSeries($number-2));
}
}
// Main Program Call
$number = 20;
for ($counter = 0; $counter < $number; $counter++){
echo fibonacciSeries($counter),' ';
}
?>
Output:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
we define the first and second number to 0 and 1 as fixed value. Following this, we display the first and second number. Then we send the flow to the iterative while loop where we get the next number by adding the previous two number and simultaneously we swap the first number with the second and the second with the third.
<?php
// PHP code to get the Fibonacci series
function fibonacciSeries($numnar){
$numnar1 = 0;
$numnar2 = 1;
$count = 0;
while ($count < $numnar){
echo ' '.$numnar1;
$numnar3 = $numnar2 + $numnar1;
$numnar1 = $numnar2;
$numnar2 = $numnar3;
$count++;
}
}
// Call Driver Code
$numnar = 20;
fibonacciSeries($numnar);
?>
Output:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
© 2024 Easy To Learning. All Rights Reserved | Design by Easy To Learning