Recursion problem

Hello there,

Can someone explain to me how the following code will output 55 if 10 is passed as an argument to pineapple?
1
2
3
4
5
6
7
int pineapple(int num)
{
    if (num <= 0)
      return 0;
    else
      return pineapple(num - 1) + num;
}
This is because, the function is called 11 times when you pass 10 as num. So in the last(11th) call, num=0, and the function returns in an order, whiles adding num. And at the end, the return int would be 55.

So basically, it is not a problem.
You can try the logic yourself and see, or post for how I got it.

Aceix.
Last edited on
Topic archived. No new replies allowed.