Skip Top Navigation Bar

Evaluating Recursion Through Tracing

Tracing can be used to evaluate a recursive method call. In this tutorial, we will explore how to use tracing to methodically interpret any recursive method call.

It is helpful to first identify the base case and the recursive call along with the reduction that is being made to reach the base case.

Computing Exponents and Recursion Example

int power(int base, int exp) {    
   if (exp == 0) 
      return 1;    
   return base * power(base, exp - 1);
}

A tree of calls can be recorded from the first call through to the base case and then fully evaluated once the base case is reached.

The call power(2, 3) returns 8.

Your Turn

Let's try it in the Java Playground.

Fibonacci and Recursion Example

Consider another recursive method example that will have multiple branches.

int fibonacci(int n) {
    if (n <= 1) {
      return n;
    }
    return fibonacci(n - 1) + fibonacci(n - 2);
}

Consider the following tracing of calls for fibonacci(5):

The call fibonacci(5) returns 5.

Your Turn

Let's try it in the Java Playground.

A tree could also be a useful visual when tracing these calls. It might look something like the following:

Complete List of Recursion Tutorials

Resources