0

I am trying to understand recursion by writing a recursive count function. One variation of the function is to count forward and other backward. I understood the backward one but not the forward one because just by changing order of statements in the else block I am able to count forward.

function countforward(num) {
    if (num == 0) {
        return 0;
    }
    else if (num == 1) {
        return console.log(1);
    }
    else {
        countforward(num - 1);
        console.log(num);
    }
}


function countbackward(num) {
    if (num == 0) {
        return 0;
    }
    else if (num == 1) {
        return console.log(1);
    }
    else {
        console.log(num);
        countbackward(num - 1);
    }
}

The backward function is clear to me because every time the control hits the else block first the number is displayed and it is reduced and called again, but i didn't get the forward function

6
  • 1
    more indentation, less perfomance ... Commented Jul 17, 2020 at 17:29
  • This code doesn't actually work, as count isn't defined. Commented Jul 17, 2020 at 17:31
  • Where is the recursion? No function is calling itself. They're calling count(), which is undefined. Commented Jul 17, 2020 at 17:31
  • the line count(num - 1); should be return count(num - 1); Commented Jul 17, 2020 at 17:39
  • @Nina Scholz why should we talk about indentation here? Commented Jul 17, 2020 at 18:15

1 Answer 1

1

Suppose we wrote a description of what each function does:

  • countforward(n) prints the values from 1 to n in ascending order
  • countbackward(n) prints the values from n to 1 in descending order

Placing these descriptions in for the respective recursive calls, we get:

else {
    countforward(n-1); // prints the values from 1 to n-1 in ascending order
    console.log(n);    // prints n
}

and

else {
    console.log(n);     // prints n
    countbackward(n-1); // prints the values from n-1 to 1 in descending order
}
    

which (hopefully) makes things clear.

Sign up to request clarification or add additional context in comments.

3 Comments

sure I edited my code, (it was a typo)but I am having a hard time to understand the forward function because when i call it with countforward(3), control hits the else block where the first statement reduces it to countforward(2) and below it the console.log statement should print n value which is 3, but i get 1
countfoward(3) prints 1,2,3 by (calling countforward(2) which prints 1,2 by (calling countforward(1) which prints 1) then prints 2) then prints 3).
Thank you. I get it now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.