Understanding recursion in the beer bottle example

后端 未结 7 1407
生来不讨喜
生来不讨喜 2020-12-21 01:37

I am practicing recursion in C on my own and I found this example online. However there is one thing I don\'t understand.

void singSongFor(int numberOfBottle         


        
7条回答
  •  臣服心动
    2020-12-21 01:44

    The reason it works in this way is that every call of the singSongFor() where numberOfBottles is more than 1 will in turn recursively call singSongFor() until numberOfBottles is 0. At this point printf("There are simply no more bottles of beer on the wall.\n\n") is reached and that function will finish, passing up to the calling function, which will have had an argument of 1 passed in, which then reaches printf("Put a bottle in the recycling, %d empty bottles in the bin.\n", numberOfBottles); and itself completes, returning to singSongFor(2)... and so on until you're back at your original number, 4 in this case.

提交回复
热议问题