educative.io

Need help about recursive function question's solution

Hi!

Could you please someone help me understand the solution of the following question?

Question:

What will be displayed when the following PHP code is executed:

   <?php
        function myFunc($value)
        {
           echo "its value is: $value";
        }
        echo "x is a variable, ";
        myFunc(4);
    ?>

The answer is 16. The explanation that follows the answer is:

At first n=2, so we function goes into the else condition, and returns 2fun(3), the function again gets called, n equals 3 this time, so again goes into the else condition and returns 2fun(4), as n=4 this time it returns n which is now equal to 2 * 2 * 2 * 2 hence the answer being 16.

I’m a little bit lost here… I thought I understood how recursive functions work but I cannot figure out why n = 2 * 2 * 2 * 2.

Any help would be very much appreciated!!

Hi K_M,
Thank you for reaching out to us on Educative’s discuss platform. In your question, I think you’ve copied the incorrect code snippet. I think you’re referring to the 3rd question in the quiz:

<?php 
function fun(int $n)
{
   if ($n == 4) return $n;
   else return 2*fun($n+1);
}
echo fun(2);
?> 

The answer to this code will in fact be 16. Here’s how:

  • When you call fun(2), the value of $n will be 2 initially
  • Then, you will call the function recursively at 2*fun(3)
  • Now, $n will be 3. The function will once again be called recursively with 2*fun(4)
  • The value of $n will be 4. Based on the condition, we will return 4.
  • In that case, 2*fun(3) will become 2 * 4 = 8. Now, we will return 8.
  • Then fun(2) will become 2 * 8 = 16 and finally, we will return 16.

In short:

  • 2*(2*(4))

You’ve raised a very useful point, however. The explanation can seem a bit misleading so we’ll update it accordingly. Thank you!

2 Likes

Thank you very much for your reply!!!

YES! I get it know! haha :smiley:
The explanation was indeed misleading, that’s why I couldn’t understood where the last two (*2) came from… :smiley:

One more thing I noticed is that when I tried to write 2 * 2 * 2 * 2 without the spaces, I see 222*2 in the preview panel on the right…

Also, you are right, I mistakenly pasted the wrong question code snippet… :slight_smile:

1 Like

You are very welcome! We are glad that you have taken the initiative to go into a lot of detail because of which not only you have improved your understanding of the course but helped many other potential learners to have a better experience as well.

Please feel free to reach out to us for any further queries!

As for your concern with regards to the asterisks not displaying correctly, that is a markdown feature. You will need to use them with spaces in between each character. If you use the asterisks without any spaces, markdown will treat those as an instruction to convert the text to italic format.

1 Like