Examples:

We are going to give two very simple examples:
Example 1:Factorial
Example 2:Linked list summation

Example 1:Factorial

The HelloWorld for recursion is to implement the factorial function, which is defined for positive integers N by the equation

N! = N × (N-1) × (N-2) × ... × 2 × 1

In other words, N! is the product of the positive integers less than or equal to N. Now, N! is easy to compute with a for loop, but an even easier method is to use the following recursive function:

public static int factorial(int N) {
if (N == 1) return 1;
return N * factorial(N-1);
}

This static method calls itself. The implementation produces the desired effect: it corresponds to rewriting the definition as

N! = N × (N-1)! = N × ((N-1) × (N-2) × ... × 2 × 1)

This equation holds for N > 1; for N = 1, factorial directly computes 1! = 1.

To compute factorial(5), it multiplies 5 by factorial(4); to compute factorial(4), it multiplies 4 by factorial(3); and so forth. This process is repeated until factorial(1), which directly returns the value 1. We can trace this computation in precisely the same way that we trace any sequence of function calls
The figure bellow shows the computing of 3!


Figure 1: 3! = 3*2! = 3*2*1
^Back to top

Linked List Summation:

Let's look at an example of recursive functions on linked lists. Suppose we have a list of numbers, and we want to sum them. Let's go through each step of the recursive sequence and identify how it applies to to our summation function:

Here is the code for the function:

int sum_list(struct list_node *l) {
if(l == NULL) return 0;
return l.data + sum_list(l.next);
}

^Back to top