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 × 1In 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!

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:
-
Initialize the algorithm. This algorithm's seed value is the first node to process and is passed as a parameter to the function.
-
Check for the base case. The program needs to check and see if the current node is the NULL list. If so, we return zero because the sum of all members of an empty list is zero.
-
Redefine the answer in terms of a simpler sub-problem. We can define the answer as the sum of the rest of the list plus the contents of the current node. To determine the sum of the rest of the list, we call this function again with the next node.
-
Combine the results. After the recursive call completes, we add the value of the current node to the results of the recursive call.
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);
}