+ 2

Can someone tell me how this code work and what it's suppose to do? I didn't understand how the input is 15

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

21st Nov 2018, 9:22 PM
ariel
ariel - avatar
9 Respuestas
+ 5
totalSum() has a call to totalSum() in it. So, given the correct condition, totalSum() is called. Think of a tree and its many branches. Use any crappy inaccurate analogy you like. However, you need to learn about recursion to understand recursion, bottom line.
21st Nov 2018, 11:17 PM
non
+ 5
Nice one David, my favorite visual example is two mirrors facing each other producing an infinite reflection of itself.
22nd Nov 2018, 12:14 AM
Da2
Da2 - avatar
+ 4
Sadly, if you cannot understand recursion, you cannot understand recursion.
21st Nov 2018, 11:09 PM
non
+ 4
ariel I think nonzyro did a great job of explaining recursion. Simply restated: Recursion occurs when a function calls itself. You can think of it as a loop construct. The method will continue to call itself until some condition is satisfied. In the code you asked about, each time the function calls itself, it decrements the parameter by 1 and continues the cycle until n==0. This is very similar to something like: int main() { int totalSum = 0; for( int i = 5; i > 0; i-- ) { totalSum = totalSum + i; } printf("%i", totalSum); return 0; }
22nd Nov 2018, 12:10 AM
David Carroll
David Carroll - avatar
+ 2
The function basically counts down to 0 and gets the sum of the numbers it encounters using recursion so... 5 + 4 = 9 9 + 3 = 12 12 + 2 = 14 14 + 1 = 15 15 + 0 = 15
21st Nov 2018, 10:13 PM
TurtleShell
TurtleShell - avatar
0
Ok but does it looping I mean why isn't it stop on 9 and just print 9
21st Nov 2018, 10:29 PM
ariel
ariel - avatar
0
If you look at the code it is recursive ie it calls itself
21st Nov 2018, 10:59 PM
John Carpenter
John Carpenter - avatar
0
Can you please explain?
21st Nov 2018, 11:01 PM
ariel
ariel - avatar
0
👍👌
21st Nov 2018, 11:27 PM
ariel
ariel - avatar