web4 Posted April 5, 2010 Share Posted April 5, 2010 <?php function getGCF($a,$b) { echo "$b<br />"; if($b==0) return $a; else return getGCF($b,$a % $b); } echo getGCF(6,10)."answer<br />"; ?> 10 6 4 2 0 2answer 10 6 4 2 0 My problem is why did 10,6,4,2,0 appear?? i thought the output would be 0,2,4,6,10 cause that's the way recursion works....like in this example.. function nfact($n) { if ($n == 0) { return 1; } else { return $n * nfact($n - 1); } } the way the recursion works in that program is they return the previous value of the function and that was my expectation in the first script...how did that happen? thanks Link to comment https://forums.phpfreaks.com/topic/197613-recursion/ Share on other sites More sharing options...
Mchl Posted April 5, 2010 Share Posted April 5, 2010 When debugging cases like this, it's useful to keep track of what your function does step bt step getGCF(6,10) $a = 6; $b = 10; -> echo $b prints '10'; getGCF(10, 6%10) is called getGCF(10, 6%10) $a = 10; $b = 6; -> echo $b prints '6'; getGCF(6,10%6) is called getGCF(6,10%6) $a = 6; $b = 4; -> echo $b prints '4'; getGCF(4,6%4) is called getGCF(4,6%4) $a = 4; $b = 2; -> echo $b prints '2'; getGCF(2,4%2) is called getGCF(2,4%2) $a = 2; $b = 0; -> echo $b prints '0'; 2 is returned Link to comment https://forums.phpfreaks.com/topic/197613-recursion/#findComment-1037198 Share on other sites More sharing options...
web4 Posted April 5, 2010 Author Share Posted April 5, 2010 Yes i know that...actually if you run that code...only the upper part will appear... i've didn't post the other codes...i solved it on my own...anyways thanks for the reply Link to comment https://forums.phpfreaks.com/topic/197613-recursion/#findComment-1037262 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.