Recursion
Can a function call itself? You bet! We call that recursion. There is a notoriously dull song called “99 Bottles of Beer.” Create a new C Command Line Tool named BeerSong. Open main.c and add a function to write out the words to this song and then kick it off in main():
#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 ...
Get Objective-C Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.