Recursion
Recursion
Recursion: -
Recursion refers to a programming technique in which a function calls
itself either directly or indirectly.
Or
Recursion is a technique for solving a large computational problem by
repeatedly applying the same procedures to reduce it to successively
smaller problems. A recursive procedure has two parts: one or more
base case and a recursive step.
Recursive definition: -
A recursive definition is a definition that is made in term of smaller
version of itself.
def compute(num):
if num == 1 :
return 1
else :
return (num + compute(num - 1))
number = 4
sum = compute(number)
For example
• The code of above program will face infinite recursion if you enter a
negative value for power. In that way condition will never be true for a
negative value of b.
Iterative version: -
For example: -
Binary search: -
Binary search can work for only sorted arrays whereas linear search can
work for both sorted as well as unsorted arrays.
RECURSION VS ITERATION: -
• Recursion makes the code short and simple while iteration makes the
code longer comparatively.
• Recursion is slower than iteration due to overhead of multiple
function calls and maintaining a stack for it.
• In iteration, the code is executed repeatedly using the same memory
space. That is, the memory space allocated once, is used for each pass
of the loop.
On the other hand in recursion, since it involves function call at each
step, fresh memory is allocated for each recursive call. For this reason
i.e., because of function call overhead, the recursive function runs
slower than its Iterative counterpart.
Thankyou!!!!!