Group 1 Data Structures and Algorithms
Group 1 Data Structures and Algorithms
ALGORITHMS
RECURSION AND
ITERATION
PRESENTED BY:
GROUP 1
INTRODUCTION
Table of Contents:
Recursion and Memory
Recursion V.S. Iteration
Examples of Recursion Algorithms
RECURSION
Recursion is a technique where a function calls itself in order
to solve a problem. It's particularly useful when a problem can be
broken down into smaller, similar subproblems.
• During this process, each function call remains in memory (in the call stack)
until it returns its result, which is why recursion can consume a lot of memory
if not managed carefully.
ITERATION
Iteration is a programming concept where a block of code is
repeated multiple times using loops like “for”, “while”, or
“do-while”. Instead of calling a function repeatedly, the program
uses a loop to execute a set of instructions until a certain condition
is met.
EXAMPLE:
EXAMPLE:
RECURSION VS.
ITERATION
Recursion and Iteration are two fundamental approaches to
solving problems that involve repetition or looping. While they
can often achieve the same result, they do so in different ways
and have different implications for performance, readability, and
memory usage.
Approach:
Recursion: A function calls itself to solve a problem. It
breaks down the problem into smaller sub-problems, solving
each sub-problem with another recursive call.
Iteration: Uses loops (for, while, etc.) to repeat a block of
code. The problem is solved by iterating over a sequence of
steps
RECURSION VS.
ITERATION
Memory Usage:
Recursion: Each recursive call adds a new layer to the call stack. This uses more
memory, especially for deep recursion, and can lead to a stack overflow if the recursion
is too deep.
Iteration: Generally uses less memory because it doesn't add new layers to the call
stack. The loop repeats within the same function, so the memory footprint is smaller.
Termination:
Recursion: Relies on a base case to stop the recursive calls. Without a proper base
case, recursion can lead to infinite loops or stack overflow.
Iteration: Relies on a loop condition to stop the loop. As long as the condition is
correctly defined, the loop will eventually terminate.
RECURSION VS.
Complexity:
ITERATION
Recursion: Can be more intuitive for problems that have a natural recursive
structure (e.g., tree traversal). However, it can be more complex to understand and
debug due to the stack of function calls.
Iteration: Often simpler and more straightforward to implement. It’s easier to
follow the flow of the loop and understand how the problem is being solved.
Performance:
Recursion: May have higher overhead due to the repeated function calls and
memory usage. In some languages, tail recursion optimization can mitigate this, but not
all recursive functions can be optimized.
Iteration: Typically faster and more efficient in terms of performance, as it avoids
the overhead of multiple function calls.
THANK
YOU!!