What is Recursion?
We will begin our course by introducing recursion.
We'll cover the following
What is Recursion?
Recursion is when a function calls itself again and again 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 Recursion?
Recursive code is generally shorter and easier to write as compared to an iterative code. In general, loops are also converted into recursive functions when they are compiled or interpreted. Recursion is most useful for tasks that can be defined in terms of similar subtasks.
Format of a Recursive Function
Each recursive function consists of parts:
-
Base Case: The base case is where further calls to the same function stop, i.e, it does not make any subsequent recursive calls.
-
Recursive Case: The recursive case is where the function calls itself again and again until it reaches the base case.
The illustration below shows the flow diagram of a recursive function:
In a recursive program, the solution to the bigger problem is expressed in terms of the smaller problems, until the smallest problem reaches the base case.
Syntax of a Recursive Function
Let’s have a look at how a recursive function is coded in 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 to returning values directly, whereas in the recursive case, we call the respective function again.
In the next lesson, we explain why this course is helpful for you.