Here, in the function call nowhere we did decrement. then how it's entering into a loop. That's what I'm not getting so anyone can help me out
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;
}
CodePudding user response:
On this line " return k sum(k - 1); " you are actually doing decrement to the actual input. So when this condition " if (k > 0) " will become false, it will exit the loop.
CodePudding user response:
Does this help?
sum(5)
= 5 sum(4)
= 5 4 sum(3)
= 5 4 3 sum(2)
= 5 4 3 2 sum(1)
= 5 4 3 2 1 sum(0)
= 5 4 3 2 1 0
= 15
That's how your code works.
CodePudding user response:
The thing is, you did decrement.
Recursion need paper and pen to be understood in the first place.
Take a paper, and start to replace the calls to sum by the code of sum, each time, then, don't forget to replace k by its value on each line.
Then you will see what happens here :)
Here is the start of what I'm asking you to do :
int sum(int k) {
if (k > 0) {
return k sum(k - 1);
} else {
return 0;
}
}
int main() {
int result = sum(10);
// So result gets
{
if (10 > 0) {
//You goes inside the if with the k = 10, so you don't have to
// write down the else clause
return 10 sum(10 - 1);
// so return got sent 10
{
//same here, k = 9, no else clause used
if (9 > 0) {
return 9 sum(9 - 1);
// And so on...
}
}
}
}
cout << result; return 0;
}