Skip Top Navigation Bar

Writing Recursion

Recursion happens when a method calls itself. This is a repetitive process that continues and progresses until a base case is reached.

There are two critical parts to a recursive method.

Without a proper progression towards the base case, the code could result in infinite recursion. This is where the program continues to call the recursive method without a stopping point.

Writing Recursion

Factorial Example

The factorial of a number, written as n!, is the product of all positive integers from 1 to n.

For example:

5! = 5 * 4 * 3 * 2 * 1

4! = 4 * 3 * 2 * 1

3! = 3 * 2 * 1

2! = 2 * 1

1! = 1

Step 1: Determine the base case

The base case is the simplest version, which is 1! since it has a defined value, which is 1.

Step 2: Break down the problem

5! = 5 * (4 * 3 * 2 * 1) or 5 * 4!

4! = 4 * (3 * 2 * 1) or 4 * 3!

3! = 3 * (2 * 1) or 3 * 2!

2! = 2 * (1) or 2 * 1!

1! = 1 --- the base case

Step 3: Generalize the recursion

In general: n! = n * (n - 1)!

The generalized recursive call, progresses toward the base case of 1 by repeated subtracting 1.

Step 4: Write your method

Check for the base case:

Consider this example of recursion for computing a sum:

To write the factorial method, we will:

Check to see if the parameter n is 1: