Tutorial by: Adam Lim
For example we need to create calculation as below:
5 => (5*2)+(4*2)+(3*2)+(2*1)+(1*1)
It can be resolved by for loop as below:
$total=0;
for($i=5; $i=0; $i--){
$total += $i * 2;
}
To create a recursive function, it should as follow:
function test($int){
if($int>0){
echo $int.<br>;
return(($int*2) + test($int-1)); // call back self function to continue loop
}else{
return 0;
}
}
echo test(5);
Output:
5
4
3
2
1
30
DEMO
No comments:
Post a Comment