+ 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
9 Answers
+ 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.
+ 5
Nice one David, my favorite visual example is two mirrors facing each other producing an infinite reflection of itself.
+ 4
Sadly, if you cannot understand recursion, you cannot understand recursion.
+ 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;
}
+ 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
0
Ok but does it looping I mean why isn't it stop on 9 and just print 9
0
If you look at the code it is recursive ie it calls itself
0
Can you please explain?
0
đđ