int sum(int n)
return n+sum(n-1); /*self call to function sum() */
Can anyone please explain to me how it sums up with the previous value each time it enters the sum(int n) function. I mean, in 'return n+sum(n-1)', how does the 'n+' part gets into the next cycle when sum(n-1) is invoked?
Best How To :
The n value doesn't go to the next cycle. The function just keeps on repeating till the n-1 value becomes 0.
When this happens, from your function, you can see that if(n==0) you will return 0, and so it return that value to the previous value for sum(1), which is n + sum(0) ~ 1 + 0.
This repeats till it finally reached the realy sum(n) value.
Hope that makes sense :)