Recursion exercise

Hi I’m struggling to understand the concept of recursion and aren’t receiving any extra help at uni.
1.
Write a recursive function to calculate: 1234…* n (i.e. multiplying the numbers from 1 to n together) where n could be any integer.
2.
Test your function by setting n to 10. Note the result should be 3628800.
3.
Now write a recursive function to generate a Fibonacci sequence with 10 numbers. The series for this task will be: 0,1,1,2,3,5,8,13,21,34. So in this series, any number is the sum of the previous two numbers.

These are my task asked to do and have looked on php manual however am still suffereing, please could someone help.

Many thanks

Well, in my humble opinion, the teacher has his/her terms confused.

Recursive functions are used when you need to loop thru items that need to call the same routine to solve the calculation. In the two calculations you need to do, they can be done by a simple loop without any need of true recursion.

But, with that said, you can use a recursive function if you really need to. You would set up the script to loop thru the process with a simple loop as I stated, but, use the function parts to call it based on the “n” number. In this case the calling line would just be function_name(10); to make the code run up to n=10. Hope that makes sense to you. So, you could do something like this for the first example:

  <?php
    //  Recursive Function Example ( Set beginning total to 1 so no multiplying by zero! )     
    function recursive1($tot, $n) {
        //  If the current number is less the target, process it...
        if($n != 0){
            //  Call the function again. decrement number by one.
            return recursive1($tot * $n, $n-1);
        } else {
            return $tot;
        }
    }
     
    //Call our recursive function.
    echo "Final total for Recursion #1 : " . recursive1(1, 10);
?>

I think this will show you how to recurse back to the same function. But, remember, when you loop like this, it takes a lot of server time if the function is complicated. One common use for this type of code is to parse thru folder structures. You can look thru folders saved inside other folders and create tress of them for use in various displays or databases. For simple calculations like this a simple FOR clause would work faster. But, they are attempting to teach you about recursion, so there you go. Hope this helps!

1 Like

can look thru folders saved inside other folders and create tress of them for use in various displays or databases. For simple calculations like this

Jonathan, what are you asking for? We gave an example, it does math, but, you can change it for folders if that is what you are asking for…

Sponsor our Newsletter | Privacy Policy | Terms of Service