Example - Printing Characters Using Both Loop and Recursion#

eyes closed emoji

We should be able to write a method to print a certain number of a given character almost with our eyes closed. Here is a version using a while loop:

public static void printNumChars(int aNum, char aChar){
   while (aNum > 0){
      System.out.print(aChar);
      aNum = aNum - 1;
   }
}

printNumChars With Recursion#

Our goal is to write the same method, but now with recursion. We want to use the method in the definition of the method. Just as a loop has conditions to end it, we must ensure that our recursive method will also end. We call the ending conditions base cases, and there must be one or more of them. Furthermore, we need to ensure that the recursive call moves us towards a base case. Notice the similarities and differences in this code to print a given character a certain number of times:

public static void printNumChars(int aNum, char aChar){
   if (aNum > 0){
      System.out.print(aChar);
      printNumChars(aNum - 1, aChar);
   }
}

Visualization of Recursive printNumChars#

How does this work? Remember that method calls use the system stack when they execute. Let’s run printNumChars(4, 'R') and see how the stack grows, and then shrinks, along with the output that is produced. We omit the return addresses for simplification.

1 Call printNumChars(4,'R')

stack with one frame of aChar and aNum

2 Call printNumChars(3,'R')

stack with two frames of aChar and aNum

3 Call printNumChars(2,'R')

stack with three frames of aChar and aNum

4 Call printNumChars(1,'R')

stack with four frames of aChar and aNum

5 Call printNumChars(0,'R')

stack with five frames of aChar and aNum

6 Return from printNumChars(0, 'R')

stack back to four frames of aChar and aNum

7 Return from printNumChars(1, 'R')

stack back to three frames of aChar and aNum

8 Return from printNumChars(2, 'R')

stack back to two frames of aChar and aNum

9 Return from printNumChars(3, 'R')

stack back to one frame of aChar and aNum

10 Return from printNumChars(4, 'R')

stack back to empty

Practice Questions#

  1. Identify the base case in the recursive method printNumChars. What happens in the base case?

  2. Explain how the recursive call in printNumChars moves the execution closer to the base case.

To Solutions