+ 2
What number will be alerted?
function func (n) { if (n<=1) { return 1; } else { return func (n-1); } } alert (func (4)); // I reasoned that n=4, which is NOT <=1, therefore, I should compute 4-1, and “3” should be alerted.
10 Answers
+ 2
Recursive function is function which will have calls itself.
func(4) is your original function call, on running this call, this function calling itself with argument 3 by fun(n-1) => fun(3),.. Until n<=1 is true, it is repeated. If you don't have this stop condition then it's infinite recursion..
1). I modified your code by adding n+(..), to understand it better.. Which does like
4 + func(3) , now this func(3) is new, independent function call, like your original calk func(4).. Until this, is not finish, then func(4) which not finished...
2) : 4 + func(3) , now you need to find func(3) to get result of this statement.
So func(4) gets the return value 4+func(3)..
func(3) gets the return value 3+ func(2).
func(2) gets return value 2+func(1).
Func(1) gets return value 1.
Go back wards to replace..
Note that, first original call is completed only after all other inner, recursives calls completed...
edit:
+ 3
Jayakrishna🇮🇳 Ok, thanks again. Sounds like I’ll need to revisit the JS lesson on recursive functions.
+ 3
Ok, I understand now. I was thinking about it completely incorrectly. I will look at those additional links. Thank you again. 🙏
+ 2
Jayakrishna🇮🇳 Thank you, but why are you returning fun (func?) three times?
+ 2
Jayakrishna🇮🇳 Thanks for your help. I’ve concluded that JavaScript needs to be reworked; it’s too confusing.
Two more questions:
1. The above is a different code (problem) than the original, correct?
2. I don’t understand why you don’t stop at 4 + func(3); is it because the function is recursive? If so, what is it that lets you know it’s recursive?
Thank you again.
+ 2
See these other examples for understanding recursion.
Hope it hepls...
https://www.sololearn.com/Discuss/3026936/?ref=app
https://www.sololearn.com/Discuss/2125616/?ref=app
+ 1
1
fun(4) => fun(3) =>fun(2) => fun(1) :: 1
+ 1
It is a recursive function.
Initially you calling fun(4) , which itself calls fun(3) due to : return fun(n-1)
, which calls fun(2) , and which calls fun(1) which just returns 1 to fun(2) call, backs to fun(3) , => fun(4) which is your statement in alert().
+ 1
I may Confused you?
Do better understand this can be modified to find the sum of n consecutive numbers like :
function func (n) {
if (n<=1)
return 1;
else
return n + func (n-1);
}
alert (func (4));
4+fun(3)
4+3+fun(2)
4+3+2+fun(1)
4+3+2+1
Result is 4+3+2+1 = 10 is returned..
Hope it helps.. You're welcome..