How is this 28? Please explain?

How is this 28? Please explain?
0

sum 7
  7 is not 1, so return 7 + sum 6
    sum 6
    6 is not 1, so return 6 + sum 5
      sum 5
      5 is not 1, so return 5 + sum 4
        sum 4
        4 is not 1, so return 4 + sum 3
          sum 3
          3 is not 1, so return 3 + sum 2
            sum 2
            2 is not 1, so return 2 + sum 1
              sum 1
              1 is 1, so return 1.
              Now you know what the value of
              `sum(1)` is, go back up:
              sum 1 is 1
            sum 2 is 2 + 1, so 3
          sum 3 is 3 + 3, so 6
        sum 4 is 4 + 6, so 10
      sum 5 is 5 + 10, so 15
    sum 6 is 6 + 15, so 21
  sum 7 is 7 + 21, so 28
return 28
2 Likes

Thanks for replying!
Very helpful!

Can I just ask, the ‘-1’ in sum(n-1), what does it do?

Hi, it’s simply there to call the sum function on a lower index. With induction, you start with an index that requires recursion and bit by bit you fall back to an index that gives you a result without recursion calls (base case).

When your n is 7, calling sum(n-1) would be like calling sum(6).

Now, when your sum(6) will be executed, the n associated to this function call will be 6.
And here, when you’ll call sum(n-1), it’ll be sum(5).

And so on until you reach the base case of your recursion, which is when n is 1 (here you return a result without a recursive call).
At this point all the previous calls will be resolved in the order opposite to how they were called (like Dan showed).

2 Likes

Big thanks to both of you @simonebogni & @DanCouper !

Much appreciated!

Sorry for my late reply.
FFC didn’t let me login. Trouble with the IP-address.
Need to reset my password every time I want to get it. :slight_smile:

1 Like