Understanding how recursive functions work

后端 未结 18 998
野性不改
野性不改 2020-11-22 07:08

As the title explains I have a very fundamental programming question which I have just not been able to grok yet. Filtering out all of the (extremely clever) \"In order to

18条回答
  •  余生分开走
    2020-11-22 07:51

    The way that I usually figure out how a recursive function works is by looking at the base case and working backwards. Here's that technique applied to this function.

    First the base case:

    sumInts(6, 5) = 0
    

    Then the call just above that in the call stack:

    sumInts(5, 5) == 5 + sumInts(6, 5)
    sumInts(5, 5) == 5 + 0
    sumInts(5, 5) == 5
    

    Then the call just above that in the call stack:

    sumInts(4, 5) == 4 + sumInts(5, 5)
    sumInts(4, 5) == 4 + 5
    sumInts(4, 5) == 9
    

    And so on:

    sumInts(3, 5) == 3 + sumInts(4, 5)
    sumInts(3, 5) == 3 + 9
    sumInts(3, 5) == 12
    

    And so on:

    sumInts(2, 5) == 2 + sumInts(3, 5)
    sumInts(4, 5) == 2 + 12
    sumInts(4, 5) == 14
    

    Notice that we've arrived at our original call to the function sumInts(2, 5) == 14

    The order in which these calls are executed:

    sumInts(2, 5)
    sumInts(3, 5)
    sumInts(4, 5)
    sumInts(5, 5)
    sumInts(6, 5)
    

    The order in which these calls return:

    sumInts(6, 5)
    sumInts(5, 5)
    sumInts(4, 5)
    sumInts(3, 5)
    sumInts(2, 5)
    

    Note that we came to a conclusion about how the function operates by tracing the calls in the order that they return.

提交回复
热议问题