What's the process behind the first and second program outputting 24 and 5 respectively? | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
+ 6

What's the process behind the first and second program outputting 24 and 5 respectively?

//first program function p(m) { if (m==1) { return m; } else { return m * p(m-1); } } alert(p(4)); //second program var x=1, y=1, z=0; do { z=x+y; } while(++x<=1 && y++>=1); z+=x+y; document.write(z)

8th Jul 2019, 4:04 AM
eMBee
eMBee - avatar
8 Réponses
+ 9
as we already know, the do while function is executed at least once. When the function is invoked in the variable z, it writes 1 + 1 and the variable x is incremented by ++x. z + = x + y = 2 + 2 + 1 = 5.
8th Jul 2019, 4:28 AM
Boboev Ahmadjon Safaralievich
Boboev Ahmadjon Safaralievich - avatar
+ 8
The first program is recursion. The function calls itself up to the base case which is m = 1. This is factorial. In function, you pass 4 as an argument. it works in that order. 4! = 4 * 3 * 2 * 1.
8th Jul 2019, 4:22 AM
Boboev Ahmadjon Safaralievich
Boboev Ahmadjon Safaralievich - avatar
+ 6
the first one simply returns the factorial of m --> 4! = 24
8th Jul 2019, 4:16 AM
Mind To Machine 💻🕆
Mind To Machine 💻🕆 - avatar
+ 5
unlike a regular while loop a do while loop executes atleast once even if the condition in the while loop is false
8th Jul 2019, 4:40 AM
Mind To Machine 💻🕆
Mind To Machine 💻🕆 - avatar
+ 4
Have you ever heard about recursion?
8th Jul 2019, 4:31 AM
Boboev Ahmadjon Safaralievich
Boboev Ahmadjon Safaralievich - avatar
+ 2
Ahmadjon Boboev, but in the second program, the "z+=x+y" shouldn't have been executed because in the while loop, ++x is not less than or equal to 1
8th Jul 2019, 4:38 AM
eMBee
eMBee - avatar
+ 1
Mind To Machine 💻🕆 I don't understand
8th Jul 2019, 4:18 AM
eMBee
eMBee - avatar
+ 1
have you ever heard the term factorial?
8th Jul 2019, 4:20 AM
Mind To Machine 💻🕆
Mind To Machine 💻🕆 - avatar