DEV Community

loading...
Cover image for Recursion

Recursion

harshita1786 profile image harshitaayyala ・1 min read

What is Recursion?

The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Recursion involves several numbers of recursive calls. However, it is important to impose a termination condition of recursion. Recursion code is shorter than iterative code however it is difficult to understand. Recursion cannot be applied to all the problems, but it is more useful for the tasks that can be defined in terms of similar subtasks. For Example, recursion may be applied to sorting, searching, and traversal problems. The idea is to represent a problem in terms of one or more smaller problems, and add one or more base conditions that stops the recursion.

What is a Recursive Function?

A recursive function performs the tasks by dividing them into subtasks. There is a termination condition defined in the function which is satisfied by some specific subtask. After this, the recursion stops, and the final result is returned from the function.

How is memory allocation of the Recursive method done?

Each recursive call creates a new copy of that method in the memory. Once some data is returned by the method, the copy is removed from the memory. Since all the variables and other stuff declared inside a function get stored in the stack, therefore a separate stack is maintained at each recursive call.

Discussion (0)

Forem Open with the Forem app