Wednesday, September 6, 2017

PHP Recursive Function


PHP also supports recursive function call like C/C++,java etc.In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function.

Example -1 :
Lets see the simple programming logic to print number using recursive function.
<?php    
function display($number) {    
    if($number<=15){    
     echo "$number <br/>";    
     display($number+1); // calling a function again     
    }  
}    
    
display(10);    
?>
Output:
---------------------------------------
10
11
12
13
14
15

Example -2 :
Lets see the simple example to find the factorial of number using recursive function.
<?php    
function factorial($n)    
{    
    if ($n < 0)    
        return -1; /*Wrong value*/    
    if ($n == 0)    
        return 1; /*Terminating condition*/    
    return ($n * factorial ($n -1));    
}    
    
echo factorial(7);    
?>
Output :
-----------------------------
5040

Example - 3 :
Lets see the simple example of Fibonacci series using the function recursion.
<?php  
/* Print fiboancci series upto 10 elements. */  
$num = 10;  
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 :
-------------------------------------

Fibonacci series using recursive function:

0 1 1 2 3 5 8 13 21 34


No comments:

Post a Comment