﻿ 对C中的递归感到困惑 - 代码日志

#### 对C中的递归感到困惑

``````#include <stdio.h>

void SingSongFor(int numberOfBottles){

if (numberOfBottles == 0){
printf("There are simply no more bottles of beer on the wall.\n\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\n", oneFewer);

SingSongFor(oneFewer); // This function calls itself!

// Print a message just before the function ends
printf("Put a bottle in the recycling, %d empty bottles in the bin.\n",numberOfBottles);
}
}

int main(int argc, const char * argv[]) {

// We could sing 99 verses, but 4 is easier to think about
SingSongFor(4);

return 0;
}
``````

There are simply no more bottles of beer on the wall.

Put a bottle in the recycling, 1 empty bottles in the bin.

Put a bottle in the recycling, 2 empty bottles in the bin.

Put a bottle in the recycling, 3 empty bottles in the bin.

Put a bottle in the recycling, 4 empty bottles in the bin.

``````void SingSongFor4(){

printf("4 bottles of beer on the wall. 4 bottles of beer.\n");

printf("Take one down, pass it around, 3 bottles of beer on the wall.\n\n");

SingSongFor3();

// Print a message just before the function ends
printf("Put a bottle in the recycling, 4 empty bottles in the bin.\n");
}
}

void SingSongFor3(){

printf("3 bottles of beer on the wall. 3 bottles of beer.\n");

printf("Take one down, pass it around, 2 bottles of beer on the wall.\n\n");

SingSongFor2();

// Print a message just before the function ends
printf("Put a bottle in the recycling, 3 empty bottles in the bin.\n");
}
}

void SingSongFor2(){

printf("2 bottles of beer on the wall. 2 bottles of beer.\n");

printf("Take one down, pass it around, 1 bottles of beer on the wall.\n\n");

SingSongFor1();

// Print a message just before the function ends
printf("Put a bottle in the recycling, 2 empty bottles in the bin.\n");
}
}

void SingSongFor1(){

printf("1 bottles of beer on the wall. 1 bottles of beer.\n");

printf("Take one down, pass it around, 0 bottles of beer on the wall.\n\n");

printf("Put a bottle in the recycling, 1 empty bottles in the bin.\n");
}
}

int main(int argc, const char * argv[]) {

// We could sing 99 verses, but 4 is easier to think about
SingSongFor4();

return 0;
}
``````