linkyndy
linkyndy

Reputation: 17900

Undefined returned from recursive function

I have the following functions defined in JavaScript:

        function rfactorial(n, f) {
            if (n == 0) {
                return f;
            }
            rfactorial(n-1, f*n);
        }

        function dofactorial(){
            var n = prompt("Enter number");
            var f = rfactorial(parseInt(n), 1);
            alert("Factorial = " + f);

            if (confirm("Do another one?")) {
                dofactorial();
            }
        }

The problem is that in dofactorial(), f is undefined. This is strange since if I check the value of f in rfactorial() it is correctly calculated right before the return. What am I doing wrong?

Upvotes: 0

Views: 65

Answers (3)

nrsharma
nrsharma

Reputation: 2562

The point is you forgot to write return before calling the function recursively

To call a function recursively it's needed to assign it's value to some variable or some parameter (it's depends on the logic). In your case you are calling rfactorial() but when it's comes in a part of recursive call it's not returning value. So you have to put return over there.

function rfactorial(n, f) {
        if (n == 0) {
            return f;
        }
       return rfactorial(n-1, f*n);  // here you forgot to include return keyword
    }

    function dofactorial(){
        var n = prompt("Enter number");
        var f = rfactorial(parseInt(n), 1);
        alert("Factorial = " + f);

        if (confirm("Do another one?")) {
            dofactorial();
        }
    }

    dofactorial();

Here is working FIDDLE.

Upvotes: 0

Progo
Progo

Reputation: 3490

Try modifying your code to this:

01| function rfactorial(n, f) {
02|    if (n == 0) {
03|       return f;
04|    }
05|    return new rfactorial(n-1, f*n);
06| }
07| function dofactorial(){
08|    var n = prompt("Enter number");
09|    var f = rfactorial(parseInt(n), 1);
10|   alert("Factorial = " + f);
11|    if (confirm("Do another one?")) {
12|    dofactorial();
13|   }
14| }

On line 3 you have 2 options return new rfactorial(n-1, f*n);, or return new rfactorial(n-1, f*n);. Both work.

Upvotes: 0

mohamed-ibrahim
mohamed-ibrahim

Reputation: 11137

function rfactorial(n, f) {
        if (n == 0) {
            return f;
        }
       return rfactorial(n-1, f*n);
    }

    function dofactorial(){
        var n = prompt("Enter number");
        var f = rfactorial(parseInt(n), 1);
        alert("Factorial = " + f);

        if (confirm("Do another one?")) {
            dofactorial();
        }
    }

    dofactorial()

Note return rfactorial(n-1, f*n); You forget return

Upvotes: 2

Related Questions