-1

I have a function like this:

function test($T0){
  $T01 = $T0-$T0/2;
  $T02 = $T0+$T0/2;
  if($T01<$T0){
    test($T01);
  } else if($T02<$T0){
    test($T02);
  } else {}
  $result = array($T01,$T02);
    return $result;
  }

  $T0 = 50;
  $result = test($T0);
  echo $result[0];

Why this function is not recursion?

Rio Eduardo
  • 175
  • 1
  • 2
  • 13

5 Answers5

2

To understand recursion you must understand recursion

You forget to return values in your ifs.

Proper code:

<?php
 function test($T0){
   $T01 = $T0-$T0/2;
   $T02 = $T0+$T0/2;
   if($T01 < $T0) return test($T01);
   else if($T02 < $T0) return test($T02);
   else return array($T01,$T02);
 }

 $T0 = 50;
 $result = test($T0);
 echo $result[0];
 ?>
Robert
  • 19,800
  • 5
  • 55
  • 85
  • You're welcome. Always remember to check every condition that may appear. Don't do else {} cause it can make infinite loop. – Robert Jul 02 '13 at 13:06
1

You are missing the return on your recursive calls:

return test($T01);

and

return test($T02);

In addition, you seem to have strange placement of braces on your else clause. Most likely it should be:

else {
    $result = array($T01,$T02);
    return $result;
}

Finally, it's worth noting that this function will (theoretically) cause your code to recurse indefinitely, as you're just dividing a positive number in 2 all the time until it reaches 0. In theory this never happens. In practice, you'll recurse to some very-very small number at which the difference with 0 will be below the floating point precision. In my test this number was 4.9406564584125E-324 (i.e. about 0.0....0494 with ... being 322 zeros).

Aleks G
  • 56,435
  • 29
  • 168
  • 265
0

You are not writing return at the end of your function call, so it is going into an infinite loop

Rohitashv Singhal
  • 4,517
  • 13
  • 57
  • 105
0

As I debug the code:

In your first condition the $T01 will become the zero each time. And then it will reach in first condition and call to again to function and you are passing the zero value that time. So the value of $T01 and $T02 becomes zero in second time and it will go in else condition. So This function will not recursion no more again.

Code Lღver
  • 15,573
  • 16
  • 56
  • 75
0

Your code is recursive only but the value of t01 is always less than t02, so its going into an infinite loop

Rohitashv Singhal
  • 4,517
  • 13
  • 57
  • 105