![]() |
VOOZH | about |
Recursion is a programming technique where a function calls itself either directly or indirectly to solve a problem. It is commonly used for:
A recursive function calls itself in its body. Let's see basic structure of recursive function:
def recursive_function(parameters):
if base_case_condition:
return base_result
else:
return recursive_function(modified_parameters)
Recursive function contains two key parts:
Example 1: This code defines a recursive function to calculate factorial of a number, where function repeatedly calls itself with smaller values until it reaches the base case.
120
Explanation:
Example 2: This code defines a recursive function to calculate nth Fibonacci number, where each number is the sum of the two preceding ones, starting from 0 and 1.
55
Explanation:
Recursion can be broadly classified into two types: tail recursion and non-tail recursion. The main difference between them is related to what happens after recursive call.
Example: This code compares tail recursion and non-tail recursion using two versions of factorial function one with an accumulator (tail-recursive) and one with multiplication after recursive call (non-tail-recursive).
120 120
Explanation:
Recursion and iteration are two common techniques used to repeat tasks in programming below table highlights the key differences between them:
| Feature | Recursion | Iteration |
|---|---|---|
| Method | A function calls itself to repeat the task | Uses loops (for, while) to repeat steps |
| Memory Use | Uses more memory due to function calls | Uses less memory |
| Performance | Usually slower because of function call overhead | Generally faster as it avoids repeated function calls |
| Best Used For | Problems like tree traversal or divide-and-conquer | Repeating steps in a sequence |
| Risk | May cause stack overflow if recursion is too deep | No stack overflow risk |