Example - Printing Characters Using Both Loop and Recursion#
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 |
2 Call |
3 Call |
4 Call |
5 Call |
6 Return from |
7 Return from |
8 Return from |
9 Return from |
10 Return from |
Practice Questions#
Identify the base case in the recursive method
printNumChars
. What happens in the base case?Explain how the recursive call in
printNumChars
moves the execution closer to the base case.