NOIDATUT FREE E LEARNING PLATFORM • AKTU B.TECH

Iteration and Recursion

Recursion uses the call stack (base nd recursive cases); tail recursion does work before the final call. Classic examples: Fibonacci and Towers of Hanoi. Iteration uses loops with lower stack space, while recursion can be clearer but risks stack overflow.


Theory & Explanation

Stack: Iteration and Recursion, Overflow & Underflow

1. Short Summary (255 Characters)

Recursion uses the call stack (base + recursive cases); tail recursion does work before the final call. Classic examples: Fibonacci and Towers of Hanoi. Iteration uses loops with lower stack space, while recursion can be clearer but risks stack overflow.

2. Stack Overflow and Stack Underflow

Because a stack (LIFO: Last-In, First-Out) has restricted access at the Top, two boundary errors occur when operations violate capacity limits[cite: 2]:

  • Stack Overflow: Occurs when a Push operation is attempted on a stack that is already full (for example, when top == MAX - 1 in a fixed-size array stack[cite: 2], when heap memory is exhausted in a linked stack[cite: 2], or when recursion depth exceeds the system call stack limit).
  • Stack Underflow: Occurs when a Pop (or Peek) operation is attempted on an empty stack (for example, when top == -1 in an array stack[cite: 2] or top == NULL in a linked stack[cite: 2]).

3. Principles of Recursion & Role of the Call Stack

Recursion is a problem-solving technique in which a function calls itself directly or indirectly on a smaller subproblem until a stopping condition is reached. Every valid recursive definition requires two essential parts:

  1. Base Case (Stopping Condition): Solves the simplest instance directly without making another recursive call, preventing infinite recursion and call-stack overflow.
  2. Recursive Case: Reduces the problem size and calls the function on that smaller subproblem, moving steadily toward the base case.

How the Call Stack Works: Each function call pushes a stack frame (activation record) containing parameters, local variables, and the return address onto the system call stack. When a base case returns, frames are popped in LIFO order and control resumes at the caller.

4. Tail Recursion

Tail Recursion is a special form of recursion where the recursive call is the very last operation performed by the function before returning—no pending arithmetic or further computation remains after the recursive call returns.

  • Advantage: Compilers supporting Tail Call Optimization (TCO) can reuse the current stack frame instead of allocating a new one, reducing stack space usage from O(n) to O(1).
  • Example: Factorial using an accumulator (tailFact(n - 1, n * acc)) multiplies during the call rather than after it returns.

5. Fibonacci Numbers (Recursive vs. Iterative)

The Fibonacci sequence starts with F(0) = 0 and F(1) = 1, and each subsequent term is the sum of the previous two: F(n) = F(n - 1) + F(n - 2) for n ≥ 2 (sequence: 0, 1, 1, 2, 3, 5, 8...).

  • Naive Recursion: Direct and readable, but recomputes overlapping subproblems repeatedly, taking exponential time O(2^n) and up to O(n) call stack depth.
  • Iterative Approach: Uses a loop with two variables to track previous terms in O(n) time and O(1) extra space.

C Program: Fibonacci (Recursive & Iterative)

#include <stdio.h>

int fibRecursive(int n) {
    if (n <= 1) return n;
    return fibRecursive(n - 1) + fibRecursive(n - 2);
}

int fibIterative(int n) {
    if (n <= 1) return n;
    int prev2 = 0, prev1 = 1, curr = 0;
    for (int i = 2; i <= n; i++) {
        curr = prev1 + prev2;
        prev2 = prev1;
        prev1 = curr;
    }
    return curr;
}

int main() {
    int n = 6;
    printf("Fibonacci(%d) Recursive: %d\n", n, fibRecursive(n));
    printf("Fibonacci(%d) Iterative: %d\n", n, fibIterative(n));
    return 0;
}

Expected Output (C):

Fibonacci(6) Recursive: 8
Fibonacci(6) Iterative: 8

Python Program: Fibonacci (Recursive & Iterative)

def fib_recursive(n):
    if n <= 1:
        return n
    return fib_recursive(n - 1) + fib_recursive(n - 2)


def fib_iterative(n):
    if n <= 1:
        return n
    prev2, prev1 = 0, 1
    for _ in range(2, n + 1):
        prev2, prev1 = prev1, prev1 + prev2
    return prev1


n = 6
print(f"Fibonacci({n}) Recursive: {fib_recursive(n)}")
print(f"Fibonacci({n}) Iterative: {fib_iterative(n)}")

Expected Output (Python):

Fibonacci(6) Recursive: 8
Fibonacci(6) Iterative: 8

6. Towers of Hanoi

The Towers of Hanoi is a classic recursive puzzle with three rods (Source, Auxiliary, and Destination) and n disks of different sizes stacked in decreasing order of size (largest at the bottom, smallest at the top). Rules:

  1. Move only one disk at a time.
  2. Only the top disk of any rod can be moved.
  3. A larger disk can never be placed on top of a smaller disk.

Recursive Strategy for n disks from S to D using A:

  1. If n == 1, move disk 1 directly from S to D (base case).
  2. Move top n - 1 disks from S to A using D as auxiliary.
  3. Move the n-th (largest) disk from S to D.
  4. Move the n - 1 disks from A to D using S as auxiliary.

Minimum moves required: 2^n - 1 (for n = 3, 2^3 - 1 = 7 moves); Time Complexity: O(2^n), Auxiliary Call Stack Space: O(n).

C Program: Towers of Hanoi

#include <stdio.h>

void towerOfHanoi(int n, char source, char auxiliary, char destination) {
    if (n == 1) {
        printf("Move disk 1 from %c to %c\n", source, destination);
        return;
    }
    towerOfHanoi(n - 1, source, destination, auxiliary);
    printf("Move disk %d from %c to %c\n", n, source, destination);
    towerOfHanoi(n - 1, auxiliary, source, destination);
}

int main() {
    int n = 3;
    towerOfHanoi(n, 'A', 'B', 'C');
    return 0;
}

Expected Output (C):

Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C

Python Program: Towers of Hanoi

def tower_of_hanoi(n, source, auxiliary, destination):
    if n == 1:
        print(f"Move disk 1 from {source} to {destination}")
        return
    tower_of_hanoi(n - 1, source, destination, auxiliary)
    print(f"Move disk {n} from {source} to {destination}")
    tower_of_hanoi(n - 1, auxiliary, source, destination)


tower_of_hanoi(3, 'A', 'B', 'C')

Expected Output (Python):

Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C

7. Tradeoffs Between Iteration and Recursion

Aspect Iteration (Loops) Recursion (Self-Calling Functions)
Control Mechanism Uses loop constructs (for, while) and explicit state variables. Uses repeated function calls managed implicitly by the call stack.
Memory / Stack Usage Generally lower memory; no per-call stack frame overhead. Higher memory due to call stack frames; deep calls risk stack overflow.
Execution Overhead Minimal loop overhead; usually faster in practice. Function call/return overhead; can be slow if subproblems repeat (e.g., naive Fibonacci).
Readability & Design Can be verbose for hierarchical or branching problems. Very natural and concise for trees, divide-and-conquer, and Towers of Hanoi.
Termination Risk Infinite loop if loop condition never becomes false. Stack overflow / infinite recursion if base case is missing or unreachable.

Diagrams

ds-diagram - Diagram

ds-diagram - Diagram

Advertisement
Advertisement