13.1 Simple Recursion: Identifying the General and Base Cases

When designing a recursive solution for a problem, we need to do two things:

  • define the base case

  • define the rule for the general case

For example, if we want to print “Hello World” 100 times, we can do the following:

  • print “Hello World” once

  • print “Hello World” 99 times

Note that we do two things: First, we print “Hello World” once, which is easy to do. Then we reduce the size of the remaining problem to printing “Hello World” 99 times. In order to print “Hello World” 99 times, we print “Hello World” once, then we print “Hello World” 98 times. Continuing the same approach, to print “Hello World” 98 times, we print “Hello World” once, then we print “Hello World” 97 times, and ...

Get Java Illuminated, 5th Edition 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.