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.
Expanding on my comments, there's nothing special with a recursive function call. It's just like any other function call.
Lets take the following example:
int c(int k)
{
return 0;
}
int b(int k)
{
return k + c(k - 1);
}
int a(int k)
{
return k + b(k - 1);
}
int main(void)
{
std::cout << a(2) << '\n';
}
The call a(2)
will do return 2 + b(1);
The call b(1)
will do return 1 + c(0);
The call c(0)
will do return 0;
This is really the same as the call sum(2)
from the recursive example in the question:
The call sum(2)
will do return 2 + sum(1);
The call sum(1)
will do return 1 + sum(0);
The call sum(0)
will do return 0;
The result is 2 + 1 + 0
which equals 3
.