variables - Recursion in C confusion -


i'm working through book includes chapter deals recursion in c. prints 99 bottles song log. here code:

void singthesong (int numberofbottles) {      if (numberofbottles == 0) {         printf("there no more bottles left.\n");     } else {         printf("%d bottles of bear on wall, %d bottles of beer.\n", numberofbottles,                numberofbottles);          int onefewer = numberofbottles - 1;          printf("take 1 down, pass around, %d bottles of beer on wall.\n", onefewer);          singthesong(onefewer);      } }  int main(int argc, const char * argv[]) {      singthesong(99);     return 0; } 

the output reads how song sang. i'm having trouble understanding is, how numberofbottles variable change value? see gets subtracted 1 in onefewer variable, i'm failing understand how working. seems me log read "99 bottles of bear on wall, 99 bottles of beer. take 1 down, pass around, 98 bottles of beer on wall." repetitively, without ever dipping below 98. i'm not sure how numberofbottles value changed, , therefore how onefewer keeps track of number of bottles. 1 more question, confusion regarding topic bad sign continuing on programming? had nailed until point.

the key here:

    int onefewer = numberofbottles - 1;     singthesong(onefewer);  

a new call singthesong generated, numberofbottles 98 instead of 99. function gets local copy of numberofbottles value of 98.

stack                                  numberofbottles ------------------------------------------------------ singthesong                            99   singthesong                          98     singthesong                        97       singthesong                      96         ...                            ...           singthesong                  1             singthesong                0 

by time numberofbottles hits zero, there 100 nested calls singthesong sitting on stack. finally, function returns without doing recursion, , copies stack waiting return 1 @ time.


Comments

Popular posts from this blog

.htaccess - First slash is removed after domain when entering a webpage in the browser -

Automatically create pages in phpfox -

c# - Farseer ContactListener is not working -