In the book "Objective-C Programming), I just did an exercise where I wrote a program in C (OSX - command line) where 99 bottles of beer song is printed to the screen. Here is the code:
Now, I see how at the line
singTheSong(oneFewer); // This function calls itself!
the function starts over at the top, with the variable "numberOfBottles is reduced by 1 to 98, and so on all the way to 0.
What I don't get is how once the song gets to the point where all the bottles are off the wall, the function then continues about the recycling, going from 1 all the way up to 99. For example, the first time the line is printed Put a bottle in the recycling, 1 empty bottles in the bin, I don't see how it gets to the next line of output where there are 2 bottles in the bin. I think it has something to do with the stack, and it is just popping off the variable at the top of the stack. Is this somewhat right?
Basically, when I look at this code, I would think (incorrectly) that it counts the bottles on the wall from 99 all the way to 0, then print about putting 1 bottle in the bin, and then the program would end.
Any help understanding how that last printf function is recursive, and am I right that it jut keeps running until all the variables in the stack are gone?
Code:
#include <stdio.h>
void singTheSong(int numberOfBottles)
{
if (numberOfBottles == 0) {
printf("There are simple bo more bottles of beer on the wall.\n");
} else {
printf("%d bottles of beer on the wall. %d bottles of beer.\n",
numberOfBottles, numberOfBottles);
int oneFewer = numberOfBottles - 1;
printf("Take one down, pass it around, %d bottles of beer on the wall.\n",
oneFewer);
singTheSong(oneFewer); // This function calls itself!
printf("Put a bottle in the recycling, %d empty bottles in the bin.\n",
numberOfBottles);
}
}
int main (int argc, const char * argv[])
{
singTheSong(99);
return 0;
}
Now, I see how at the line
singTheSong(oneFewer); // This function calls itself!
the function starts over at the top, with the variable "numberOfBottles is reduced by 1 to 98, and so on all the way to 0.
What I don't get is how once the song gets to the point where all the bottles are off the wall, the function then continues about the recycling, going from 1 all the way up to 99. For example, the first time the line is printed Put a bottle in the recycling, 1 empty bottles in the bin, I don't see how it gets to the next line of output where there are 2 bottles in the bin. I think it has something to do with the stack, and it is just popping off the variable at the top of the stack. Is this somewhat right?
Basically, when I look at this code, I would think (incorrectly) that it counts the bottles on the wall from 99 all the way to 0, then print about putting 1 bottle in the bin, and then the program would end.
Any help understanding how that last printf function is recursive, and am I right that it jut keeps running until all the variables in the stack are gone?