...

/

The Structure of a Recursive Program

The Structure of a Recursive Program

Learn how to recursively solve a problem in programming.

A recursive method

Any Java method that calls itself is a recursive method.

Allowing a method to call itself isn’t very simple. We need to decide when to stop calling the method, to solve the problem recursively. Otherwise, we’ll get stuck in an infinite loop.

Cases of a recursive method

There are two parts of a recursive method:

  1. Base case
  2. Recursive case

Before writing any recursive method, we always have to find the base case and recursive case of a problem. The base case is responsible for halting the recursion. The base case is referred to as the solution to the smallest problem.

Every recursive method contains at least one base case and at least one recursive call (method calling itself).

Example

Let’s write a basic recursive program to clear any confusions. Suppose we want to write a basic program that prints the first n numbers (1,...,n1, ..., n ...