dslreports logo
site
 
    All Forums Hot Topics Gallery
spc

spacer




how-to block ads


Search Topic:
share rss forum feed


cdru
Go Colts
Premium,MVM
join:2003-05-14
Fort Wayne, IN
kudos:7
reply to cplusnoob

Re: Please help me understand this function

said by cplusnoob :

cdru, I understand the purpose of the function, I just don't understand how it actually works to achieve the result. It's calling itself over and over with one less number each time until the number is 2. How are those answers being returned as the correct answer if the only way to break the cycle is by having the variable be 2?

It's calling the function recursively.

For values of 0 and 1, it sounds like you understand. If 2 is initially passed in, before it can return the value it calls the same function with n-1 (2-1 = 1) and n-2 (2-2=0). Those two calls return 1 and 0 respectively. It adds those up and returns the sum, 1.

For a more complicated example, pass in 6. That would make recursive calls to n=5 and n=4. Then 4, 3; 3, 2. Then 3, 2; 2, 1; 2, 1; 1, 0. Then 2, 1; 1, 0; 1, 0. Then 1, 0. Each call adding up the returned value then finally returning the final value to display.