17.4. Recursive Countdown¶
If asked to write a static method to countdown from a specified value to zero, you would likely write a for-loop and create a method that looks something like this:
public static void countFrom(int value) {
for(int i = value; i > 0; i--) {
System.out.println(i);
} // for
} // countFrom
Here is a trace of the code above:
countFrom(5):
i = 5: print(5) then i--
i = 4: print(4) then i--
i = 3: print(3) then i--
i = 2: print(2) then i--
i = 1: print(1) then i--
i = 0: loop condition no longer met
You might also see a recursive solution to this problem! Can you identify the recursive cases (sub-problems) and base cases? Take a second to think about it before reading ahead
You may have come up with a problem decomposition similar to the following:
countFrom(5): print(5) then call countFrom(4)
countFrom(4): print(4) then call countFrom(3)
countFrom(3): print(3) then call countFrom(2)
countFrom(2): print(2) then call countFrom(1)
countFrom(1): print(1) then call countFrom(0)
countFrom(0): simply return
If countFrom
is passed any value other than 0
, we are in the
recursive case where the method prints its current value and then calls
itself with the value minus one. This will eventually lead to the base
case and each call to countFrom
works on a smaller version of the
original problem (a smaller sequence to print).
Take a few minutes to think about what the code for this might look like
One Possible Solution:
public static void countFrom(int num) {
// Base Case
if (num == 0) {
return;
} // if
// Recursive Case
System.out.println(num);
countFrom(num - 1);
} // countFrom
Try out the above method. Call it from your main
method using
various input values to make sure it’s working properly.