+ 1

Who is help me explain it why is output 1

https://code.sololearn.com/Weva38sQ8zTw/?ref=app

11th Sep 2020, 5:48 PM
Тимур Завьялов
Тимур Завьялов - avatar
14 Antworten
+ 3
It Outputs one because the function is called over and over, until the n <= 1 When n <= 1, It returns 1
11th Sep 2020, 6:02 PM
Steve Sajeev
Steve Sajeev - avatar
+ 2
Pls send the code of resulting in 3
11th Sep 2020, 6:23 PM
Steve Sajeev
Steve Sajeev - avatar
+ 2
Тимур Завьялов you need to understand and look at your code carefully ,in the following code you just posted ,no call to function is being made again and again , function is simply called once with func(4) which checks if 4<=1 ,if yes return 1 else return n-1 which results in 3 as in the previous code you were calling function again and again by return func(n-1) instead of n-1 ,notice the difference now?
11th Sep 2020, 6:40 PM
Abhay
Abhay - avatar
+ 2
Abhay, thank you, I understood, I don't understand what's difference between "return" and "return func". Now I got it :)
11th Sep 2020, 6:49 PM
Тимур Завьялов
Тимур Завьялов - avatar
+ 2
Тимур Завьялов glad you got it ,your welcome!!✌️
11th Sep 2020, 6:50 PM
Abhay
Abhay - avatar
+ 2
I was not able to comment yesterday, sorry ANY WAY YOU GOT THE ANSWER
12th Sep 2020, 2:32 AM
Steve Sajeev
Steve Sajeev - avatar
+ 2
Recursion could be tricky for someone who is trying it for first time. Due to recursion your function func() is executing again and again. let's break how your code is working. when you call the statement: alert(func(4)) the JS starts to executing your function. func(4) return another function func(3), func(3) return func(2) func(2) return func(1) and func(1) returns 1. and this same procedure will go for all the functions return by the func(4) which means you will be getting 1 for each function func(1), func(2), func(3) and func(4). but you are doing nothing with the return value, as a result you get only func(4) last return value as 1.
12th Sep 2020, 7:35 AM
Vinay Khatri
Vinay Khatri - avatar
+ 2
Answer is right. Because, this function has ability to call itself over over until n <= 1. And that's why this function has a special name called "Recursive Function".
13th Sep 2020, 3:29 AM
Rudro Saha🇧🇩
Rudro Saha🇧🇩 - avatar
+ 1
Steve, why if you remove "func" of return it outputs 3?
11th Sep 2020, 6:09 PM
Тимур Завьялов
Тимур Завьялов - avatar
11th Sep 2020, 6:29 PM
Тимур Завьялов
Тимур Завьялов - avatar
+ 1
I don't understand what is the difference
11th Sep 2020, 6:30 PM
Тимур Завьялов
Тимур Завьялов - avatar
+ 1
Steve, no big deal :)
12th Sep 2020, 2:55 AM
Тимур Завьялов
Тимур Завьялов - avatar
+ 1
Vinay, thank you)
12th Sep 2020, 11:35 AM
Тимур Завьялов
Тимур Завьялов - avatar
+ 1
The code is so designed that 1) if condition is true it would return 1 2) if condition is false it would call itself once again with (n-1). So we have coded it in such a way that it has to decrement 'n' until it is =1.
13th Sep 2020, 2:13 PM
Krishna