本から C を学ぼうとしていますが、明確に説明されていないことがあります。
次のコード
1) 再帰関数を使用して、ビールのボトルを 99 から 0 までカウントダウンします。2) ボトルがなくなると、「壁にもうボトルはありません」と表示され、3) ボトルを 1 つずつリサイクルに入れます。
... #more of same above
3 bottles of beer on wall, 3 bottles of beer
Take one down, pass around, 2 bottls of beer
2 bottles of beer on wall, 2 bottles of beer
Take one down, pass around, 1 bottls of beer
1 bottles of beer on wall, 1 bottles of beer
Take one down, pass around, 0 bottls of beer
There are no more bottles on the wall.
Put bottle in recycling, 1 empty bottles in bin
Put bottle in recycling, 2 empty bottles in bin
Put bottle in recycling, 3 empty bottles in bin
.... #pattern continues
カウントダウンの方法と、ビールのボトルがなくなったと表示される理由は理解できますが、ボトルをリサイクルに入れるためのコード (printf) がどのように呼び出されるかはわかりません。そして、ボトルの数が 0 に達すると、関数は条件の else 部分に戻ることはありません。
質問、最終的な printf (「ボトルをリサイクルに入れます...」) はどのようにして 99 回呼び出され、どのようにしてボトルを 1 つずつインクリメントできるのでしょうか?
コード
void singTheSong(int numberOfBottles)
{
if(numberOfBottles == 0){
printf("There are no more bottles on the wall.\n");
}else {
printf("%d bottles of beer on wall, %d bottles of beer \n", numberOfBottles,numberOfBottles);
int oneFewer = numberOfBottles - 1;
printf("Take one down, pass around, %d bottls of beer \n", oneFewer);
singTheSong(oneFewer);
printf("Put bottle in recycling, %d empty bottles in bin \n", numberOfBottles);
}
}
int main(int argc, const char * argv[])
{
singTheSong(99);
return 0;
}