I was going through this recursion program in cpp on w3schools.
#include <iostream>
using namespace std;
int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
int main() {
int result = sum(10);
cout << result;
return 0;
}
There is a condition block in the recursive function above.
Assuming that it will eventually go to the 'else' block, the value of 0
will be returned from the function.
However, it's confusing to me how the function call sum(10)
is working properly and not just returning 0
.
Could someone explain the recursion to me.