1.1. An Illustration of the Recursive Approach

Let's imagine that you have recently accepted the position of funding coordinator for a local election campaign and must raise $1000 from the party faithful. In this age of political action committees and direct-mail appeals, the easiest approach is to find a single donor who will contribute the entire amount. On the other hand, the senior campaign strategists (fearing that doing so might be interpreted as a lack of commitment to democratic values), have insisted that the entire amount be raised in contributions of exactly $1. How would you proceed?

Certainly, one solution to this problem is to go out into the community, find 1000 supporters, and solicit $1 from each. In programming terms, such a solution has the following general structure:

void collect1000() { 
    for (int i = 0; i < 1000; i++) { 
       Collect one dollar from person i .
    } 
} 

Because this code uses an explicit iterative construct—in this case, a for loop, though in other contexts it could be a while—to express the overall control structure, this strategy is called an iterative solution.

Assuming that you could find a thousand people on your own, this solution would be effective, but not easy. The entire process would be considerably less exhausting if you could divide the task into smaller components, which you could then delegate to other volunteers. For example, you might enlist ten people to each raise $100. From the perspective of each volunteer, the new problem has ...

Get Thinking Recursively with Java 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.