Understanding how recursive functions work

后端 未结 18 997
野性不改
野性不改 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:36

    Think recursion as a multiple clones doing same thing...

    You ask to clone[1]: "sum numbers between 2 and 5"

    + clone[1]               knows that: result is 2 + "sum numbers between 3 and 5". so he asks to clone[2] to return: "sum numbers between 3 and 5"
    |   + clone[2]           knows that: result is 3 + "sum numbers between 4 and 5". so he asks to clone[3] to return: "sum numbers between 4 and 5"
    |   |   + clone[3]       knows that: result is 4 + "sum numbers between 5 and 5". so he asks to clone[4] to return: "sum numbers between 5 and 5"
    |   |   |   + clone[4]   knows that: result is 5 + "sum numbers between 6 and 5". so he asks to clone[5] to return: "sum numbers between 6 and 5"
    |   |   |   |   clone[5] knows that: he can't sum, because 6 is larger than 5. so he returns 0 as result.
    |   |   |   + clone[4]   gets the result from clone[5] (=0)  and sums: 5 + 0,  returning 5
    |   |   + clone[3]       gets the result from clone[4] (=5)  and sums: 4 + 5,  returning 9
    |   + clone[2]           gets the result from clone[3] (=9)  and sums: 3 + 9,  returning 12
    + clone[1]               gets the result from clone[2] (=12) and sums: 2 + 12, returning 14
    

    and voilá!!

提交回复
热议问题