Anshul Kumar
Anshul Kumar

Reputation: 7

In Recursion without a decrement how it's entering a loop

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;
}

Upvotes: -1

Views: 69

Answers (3)

john
john

Reputation: 87962

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.

Upvotes: 2

Elley
Elley

Reputation: 970

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;
}

Upvotes: 0

Zohair
Zohair

Reputation: 59

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.

Upvotes: 3

Related Questions