horald Henry

horald Henry

  • 1.7k
  • 20
  • 1k

C difficulty recursion

Mar 13 2023 1:54 PM

I'd want to ask you a question concerning recursion in the C programming language. I'm reading a c book and came across some code that I didn't fully grasp.

first questions:

void singTheSong(int numberOfBottles)
{
  if (numberOfBottles == 0)
  {
    printf("There are simply no 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;
}

So this is meant to be a song. I understand the if clause. I'm not sure how the number goes from 0 to 98.

second question:

printf("Put a bottle in the recycling, %d empty bottles in the bin.\n",
numberOfBottles);

Why isn't it increasing to 99? It comes to an end at 98. Please explain in basic English, as I do not speak English as my first language (some difficulties)

According to one of the article I read, everything before singTheSong() is run, and then the recursive call occurs, creating a new stack frame. There will be no recycling print statements until numberOfBottles reaches 0.


Answers (3)