What is Recursion?

We will begin this course by introducing the concept recursion.

What is Recursion?

Recursion occurs when a function calls itself repeatedly until it reaches a specified stopping condition. Such a function is called a recursive function.

Recursion is the process of describing an action in terms of itself.

Why use Recursion?

The following are the reasons why we use recursion:

  • Recursive code is generally shorter and easier to write than iterative code.
  • Recursion is most useful for tasks that can be defined in terms of similar subtasks.

Format of a Recursive Function

A recursive function consists of 22 main parts:

  • Base Case: The base case is where all further calls to the same function stop, meaning that it does not make any subsequent recursive calls.

  • Recursive Case: The recursive case is where the function calls itself repeatedly until it reaches the base case.

The illustration below displays the flow diagram of a recursive function:

Code flow of a recursive function
Code flow of a recursive function

In a recursive function, the solution to the main problem is expressed in terms of smaller problems until the smallest problem reaches the base case.

Syntax of a Recursive Function

Let’s take a look at how to code a recursive function using Python:

def RecursiveFunction() :
  # Base Case
  if <baseCaseCondition> :
    <return some base case value>

  # Recursive Case
  else :
    <return(recursive call and any other task)>

The base case leads directly to its returning values, whereas, in the recursive case, we call the respective function again.


In the next lesson, we explain why this course is helpful for you.